java如何追加写入txt文件

java如何追加写⼊txt⽂件java中,对⽂件进⾏追加内容操作的三种⽅法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
//如果⽂件存在,则追加内容;如果⽂件不存在,则创建⽂件,追加内容的三种⽅法public class AppendContentToFile {
@SuppressWarnings("static-access")
public static void main(String[] args) {
AppendContentToFile a = new AppendContentToFile();
}
⽅法1:1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20public void method1() {
FileWriter fw = null;
try{
//如果⽂件存在,则追加内容;如果⽂件不存在,则创建⽂件File f=new File("E:\\dd.txt");
fw = new FileWriter(f, true);
} catch(IOException e) {
e.printStackTrace();
}
PrintWriter pw = new PrintWriter(fw);
pw.println("追加内容");
pw.flush();
try{
fw.flush();
pw.close();
fw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
⽅法2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16public static void method2(String file, String conent) { BufferedWriter out = null;
try{
out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file, true)));
out.write(conent+"\r\n");
} catch(Exception e) {
e.printStackTrace();
} finally{
try{
out.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
⽅法3:1
scm文件
2 3public static void method3(String fileName, String content) { try{
// 打开⼀个随机访问⽂件流,按读写⽅式
4 5 6 7 8 9 10 11 12 13 14 15RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); // ⽂件长度,字节数
long fileLength = randomFile.length();
// 将写⽂件指针移到⽂件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content+"\r\n");
randomFile.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}

本文发布于:2024-09-22 03:50:18,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/4/381767.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

下一篇:l详解
标签:追加   内容   存在   访问   长度   打开   字节数   创建
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议