当前位置:   article > 正文

java写入文件的几种方法(一)_java文件输入流的使用

java文件输入流的使用

1. FileWritter写入文件

FileWritter, 字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容,如下:

new FileWriter(file);

然而,当指定一个true (Boolean)值作为FileWritter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾,如下:

new FileWriter(file,true);

举个例子:

一个文件名为test_appendfile.txt,包含以下内容:Hello World,需要追新内容,代码如下:

  1. package com.andy.file;
  2. import java.io.File;
  3. import java.io.FileWriter;
  4. import java.io.BufferedWriter;
  5. import java.io.IOException;
  6. public class AppendToFileTest
  7. {
  8. public static void main( String[] args )
  9. {
  10. try{
  11. String content = "A cat will append to the end of the file";
  12. File file =new File("test_appendfile.txt");
  13. if(!file.exists()){
  14. file.createNewFile();
  15. }
  16. //使用true,即进行append file
  17. FileWriter fileWritter = new FileWriter(file.getName(),true);
  18. fileWritter.write(content);
  19. fileWritter.close();
  20. System.out.println("finish");
  21. }catch(IOException e){
  22. e.printStackTrace();
  23. }
  24. }
  25. }

执行结果:

可打开文本文件“test_appendfile.txt”,内容更新如下:

Hello world A cat will append to the end of the file

2.BufferedWriter写入文件

缓冲字符(BufferedWriter )是一个字符流类来处理字符数据, 但又不同于字节流(数据转换成字节),你可以直接写字符串,数组或字符数据保存到文件。

  1. package com.andy.file;
  2. import java.io.BufferedWriter;
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. public class WriteToFileTest2 {
  7. public static void main(String[] args) {
  8. try {
  9. String content = "a dog will be write in file";
  10. File file = new File("test_appendfile2.txt");
  11. if(!file.exists()){
  12. file.createNewFile();
  13. }
  14. FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
  15. BufferedWriter bw = new BufferedWriter(fileWriter);
  16. bw.write(content);
  17. bw.close();
  18. System.out.println("finish");
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. }

执行完后,打开test_appendfile2.txt文件即可看到。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/538334
推荐阅读
相关标签
  

闽ICP备14008679号