永发信息网

java文件读写 在一个已经有内容的文件中追加第一行 如何做到

答案:2  悬赏:80  手机版
解决时间 2021-04-06 02:37
  • 提问者网友:活着好累
  • 2021-04-05 11:40
java文件读写 在一个已经有内容的文件中追加第一行 如何做到
最佳答案
  • 五星知识达人网友:患得患失的劫
  • 2021-04-05 12:24
如果要在已有内容的文件开头插入内容就只能先把原内容读出来,然后先写入要插入的东西,然后再把原内容写回去,然后关闭输出流
如果要在已有内容的文件末尾追加内容就比较简单了
在创建FileOutputStream对象的时候第二个参数给个true,就表示续写文件,而非覆盖文件已有内容了
new FileOutputStream(file, true)
全部回答
  • 1楼网友:夜余生
  • 2021-04-05 12:31
代码如下: import java.io.filewriter; import java.io.ioexception; import java.io.randomaccessfile; public class appendtofile { public static void appendmethoda(string filename, string content){ try { // 打开一个随机访问文件流,按读写方式 randomaccessfile randomfile = new randomaccessfile(filename, "rw"); // 文件长度,字节数 long filelength = randomfile.length(); //将写文件指针移到文件尾。 randomfile.seek(filelength); randomfile.writebytes(content); randomfile.close(); } catch (ioexception e){ e.printstacktrace(); } } public static void appendmethodb(string filename, string content){ try { //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 filewriter writer = new filewriter(filename, true); writer.write(content); writer.close(); } catch (ioexception e) { e.printstacktrace(); } } public static void main(string[] args) { string filename = "c:/temp/newtemp.txt"; string content = "new append!"; //按方法a追加文件 appendtofile.appendmethoda(filename, content); appendtofile.appendmethoda(filename, "append end. \n"); //显示文件内容 readfromfile.readfilebylines(filename); //按方法b追加文件 appendtofile.appendmethodb(filename, content); appendtofile.appendmethodb(filename, "append end. \n"); //显示文件内容 readfromfile.readfilebylines(filename); } } 希望采纳
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯