java如何追加写入txt文件

java如何追加写入txt文件,第1张

java追加写入txt文件代码及注释参考如下:

public void m() {

FileWriter ff= null

try {

//查看C盘是否有a.txt文件来判定是否创建

File f=new File("c:\\a.txt")

ff = new FileWriter(f, true)//将字节写入文件末尾处,相当于追加信息。

} catch (IOException e) {

e.printStackTrace()

}

PrintWriter p = new PrintWriter(ff)

p.println("这里就可以写入要追加的内容了")//此处为追加内容

p.flush()

ff.try {

f.flush()

p.close()

ff.close()

} catch (IOException e) {

e.printStackTrace()

}

}

首先创建一个新的txt文件,然后new File(“txt文件路径”),

封装一个输入输出流,将要写入的数据写入到txt中,刷新流,关闭流。

代码如下:

public static void main(String[] args) throws IOException{

String str = "这个项目什么时候上线"

File file//创建文件夹

FileOutputStream stream = null//new文件流

try {

file = new File("C:/Users/qisf/Desktop/Aa.txt")

stream = new FileOutputStream (file)//将文件夹放在文件流中

if (!file.exists()) {

file.createNewFile()

}

byte[] contentInBytes = str.getBytes()//转化成字节形

stream.write(contentInBytes)//写入

stream.flush()//写完之后刷新

stream.close()//关闭流

} catch (FileNotFoundException e) {

e.printStackTrace()

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11905511.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-19
下一篇2023-05-19

发表评论

登录后才能评论

评论列表(0条)

    保存