java在文件尾部追加内容的简单实例

网友投稿 306 2023-06-25


java在文件尾部追加内容的简单实例

如下所示:

import java.io.FileWriter;

import java.io.IOException;

import java.io.RandomAccessFile;

/**

* 将内容追加到文件尾部.

* @author haicheng.cao

*

*/

public class AppendToFile {

/**

* A方法追加文件:使用RandomAccessFile

*/

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();

}

}

/**

* B方法追加文件:使用FileWriter

*/

public static void appendMethodB(String fileName, String content) {

try {

//打开一个写http://文件器,构造函数中的第二个参数true表示以追加形式写文件

FileWriter writer = new FileWriter(fileName, true);

writer.write(chttp://ontent);

writer.close();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

String fileName = "C:/temp/newTemp.txt";

String content = "new append!";

//按方法A追加文件

AppendToFilecfIfeCCO.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);

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:浅谈java中的TreeMap 排序与TreeSet 排序
下一篇:java.lang.NoSuchMethodException: com.sun.proxy.$Proxy58.list错误解决办法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~