java在文件尾部追加内容的简单实例
如下所示:
importjava.io.FileWriter;
importjava.io.IOException;
importjava.io.RandomAccessFile;
/**
*将内容追加到文件尾部.
*@authorhaicheng.cao
*
*/
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表示以追加形式写文件
FileWriterwriter=newFileWriter(fileName,true);
writer.write(content);
writer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
StringfileName="C:/temp/newTemp.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在文件尾部追加内容的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。