java 将字符串追加到文件已有内容后面的操作
我就废话不多说了,大家还是直接看代码吧~
/**
*将字符串追加到文件已有内容后面
*
*@paramfileFullPath文件完整地址:D:/test.txt
*@paramcontent需要写入的
*/
publicstaticvoidwriteFile(StringfileFullPath,Stringcontent){
FileOutputStreamfos=null;
try{
//true不覆盖已有内容
fos=newFileOutputStream(fileFullPath,true);
//写入
fos.write(content.getBytes());
//写入一个换行
fos.write("\r\n".getBytes());
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(fos!=null){
try{
fos.flush();
fos.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
补充知识:java写文件时往末尾追加文件(而不是覆盖原文件),的两种方法总结
代码如下:
importjava.io.FileWriter;
importjava.io.IOException;
importjava.io.RandomAccessFile;
publicclassAppendToFile{
/**
*A方法追加文件:使用RandomAccessFile
*/
publicstaticvoidappendMethodA(StringfileName,Stringcontent){
try{
//打开一个随机访问文件流,按读写方式
RandomAccessFilerandomFile=newRandomAccessFile(fileName,"rw");
//文件长度,字节数
longfileLength=randomFile.length();
//将写文件指针移到文件尾。在该位置发生下一个读取或写入操作。
randomFile.seek(fileLength);
//按字节序列将该字符串写入该文件。
randomFile.writeBytes(content);
//关闭此随机访问文件流并释放与该流关联的所有系统资源。
randomFile.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*B方法追加文件:使用FileWriter
*/
publicstaticvoidappendMethodB(StringfileName,Stringcontent){
try{
//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件,如果为true,则将字节写入文件末尾处,而不是写入文件开始处
FileWriterwriter=newFileWriter(fileName,true);
writer.write(content);
writer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
StringfileName="C:/Temp.txt";
Stringcontent="newappend!";
//按方法A追加文件
AppendToFile.appendMethodA(fileName,content);
AppendToFile.appendMethodA(fileName,"appendend.\n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
//按方法B追加文件
AppendToFile.appendMethodB(fileName,content);
AppendToFile.appendMethodB(fileName,"appendend.\n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
}
}
java控制台输出结果如下:
++++++readFileByLines:++++++
以行为单位读取文件内容,一次读一整行:
line1:SunYat-sen(November12,1866–March12,1925)wasaChineserevolutionaryandpoliticalleaderwhoisoftenreferredtoasthe"fatherofmodernChina".SunplayedaninstrumentalandleadershiproleintheeventualoverthrowoftheQingDynastyin1911.HewasthefirstprovisionalpresidentwhentheRepublicofChinawasfoundedin1912.Helaterco-foundedtheKuomintang(KMT)whereheservedasitsfirstleader.newappend!appendend.
++++++readFileByLines:++++++
以行为单位读取文件内容,一次读一整行:
line1:SunYat-sen(November12,1866–March12,1925)wasaChineserevolutionaryandpoliticalleaderwhoisoftenreferredtoasthe"fatherofmodernChina".SunplayedaninstrumentalandleadershiproleintheeventualoverthrowoftheQingDynastyin1911.HewasthefirstprovisionalpresidentwhentheRepublicofChinawasfoundedin1912.Helaterco-foundedtheKuomintang(KMT)whereheservedasitsfirstleader.newappend!appendend.line2:newappend!appendend.
以上这篇java将字符串追加到文件已有内容后面的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。