【问题标题】:How to add a new line of text to an existing file in Java? [duplicate]如何在 Java 中的现有文件中添加新的文本行? [复制]
【发布时间】:2011-06-04 14:16:06
【问题描述】:

我想在现有文件中追加一个新行,而不删除该文件的当前信息。简而言之,这是我使用当前时间的方法:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;

Writer output;
output = new BufferedWriter(new FileWriter(my_file_name));  //clears file every time
output.append("New Line!");
output.close();

上面几行的问题只是他们删除了我现有文件的所有内容,然后添加了新的行文本。

我想在文件内容的末尾附加一些文本而不删除或替换任何内容。

【问题讨论】:

    标签: java file-io text-processing


    【解决方案1】:

    你必须以追加模式打开文件,这可以通过使用FileWriter(String fileName, boolean append)构造函数来实现。

    output = new BufferedWriter(new FileWriter(my_file_name, true));
    

    应该做的伎俩

    【讨论】:

    • 非常感谢!请问有没有办法在每次输出后附加(“\ n”)?如您所知,它将所有内容附加在一行中,而忽略了我的“\ n”转义!
    • BufferedWriter 有一个 newLine() 方法。您可以使用它,或者改用PrintWriter,它提供了println() 方法
    • 谢谢!但是由于一些奇怪的原因,当我尝试使用: output.newLine() |方法列表中不存在。我正在使用 NetBeans 6.9。所有其他方法都在那里。你知道这可能是什么原因吗?
    • 是的,您将output 存储为Writer,这是一个较小的接口。如果您想访问该方法,则必须将其显式存储为 BufferedWriter output
    • BufferedWriter 不会隐式执行任何魔法。您需要调用 newLine() 方法,然后才调用它。在此处查看完整代码。 try(FileWriter fw=new FileWriter("/home/xxxx/playground/coivd_report_02-05-2021.txt",true); BufferedWriter bw= new BufferedWriter(fw)){ bw.newLine(); bw.append("当这个 COVID 结束时"); }catch (IOException 异常){ System.out.println(exception); }
    【解决方案2】:

    FileWriter 的解决方案正在运行,但是您无法指定输出编码,在这种情况下将使用机器的默认编码,这通常不是 UTF-8!

    所以最好使用FileOutputStream

        Writer writer = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(file, true), "UTF-8"));
    

    【讨论】:

    • 别忘了关闭FileOutputStream
    • 这个解决方案解决了追加存在 utf-8 文件的问题。
    【解决方案3】:

    Java 7开始:

    定义一个路径和开头包含行分隔符的String:

    Path p = Paths.get("C:\\Users\\first.last\\test.txt");
    String s = System.lineSeparator() + "New Line!";
    

    然后您可以使用以下方法之一:

    1. 使用Files.write(小文件):

      try {
          Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
      } catch (IOException e) {
          System.err.println(e);
      }
      
    2. 使用Files.newBufferedWriter(文本文件):

      try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
          writer.write(s);
      } catch (IOException ioe) {
          System.err.format("IOException: %s%n", ioe);
      }
      
    3. 使用Files.newOutputStream(可与java.io API 互操作):

      try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
          out.write(s.getBytes());
      } catch (IOException e) {
          System.err.println(e);
      }
      
    4. 使用Files.newByteChannel(随机访问文件):

      try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
          sbc.write(ByteBuffer.wrap(s.getBytes()));
      } catch (IOException e) {
          System.err.println(e);
      }
      
    5. 使用FileChannel.open(随机访问文件):

      try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) {
          sbc.write(ByteBuffer.wrap(s.getBytes()));
      } catch (IOException e) {
          System.err.println(e);
      }
      

    有关这些方法的详细信息,请参阅Oracle's tutorial

    【讨论】:

      【解决方案4】:

      试试:“\r\n

      Java 7 示例:

      // append = true
      try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true))) 
      {
          output.printf("%s\r\n", "NEWLINE");
      } 
      catch (Exception e) {}
      

      【讨论】:

      • \r\n 适用于 Windows。最好使用“line.separator”属性
      【解决方案5】:

      如果您正在寻找一种创建和写入文件的剪切和粘贴方法,这是我写的一个只接受字符串输入的方法。如果您想每次都覆盖文件,请从 PrintWriter 中删除“true”。

      private static final String newLine = System.getProperty("line.separator");
      
      private synchronized void writeToFile(String msg)  {
          String fileName = "c:\\TEMP\\runOutput.txt";
          PrintWriter printWriter = null;
          File file = new File(fileName);
          try {
              if (!file.exists()) file.createNewFile();
              printWriter = new PrintWriter(new FileOutputStream(fileName, true));
              printWriter.write(newLine + msg);
          } catch (IOException ioex) {
              ioex.printStackTrace();
          } finally {
              if (printWriter != null) {
                  printWriter.flush();
                  printWriter.close();
              }
          }
      }
      

      【讨论】:

        【解决方案6】:

        在第 2 行将new FileWriter(my_file_name) 更改为new FileWriter(my_file_name, true),这样您就可以附加到文件而不是覆盖。

        File f = new File("/path/of/the/file");
                try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
                    bw.append(line);
                    bw.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
        

        【讨论】:

          【解决方案7】:

          如果要将数据附加到文件,可以使用FileWriter(String fileName, boolean append) 构造函数。

          将您的代码更改为:

          output = new BufferedWriter(new FileWriter(my_file_name, true));
          

          来自 FileWriter javadoc:

          构造一个给定的 FileWriter 对象 文件名。如果第二个参数是 true,然后字节将被写入 文件的结尾而不是 开始。

          【讨论】:

            猜你喜欢
            • 2012-10-21
            • 1970-01-01
            • 2019-08-22
            • 1970-01-01
            • 1970-01-01
            • 2018-02-06
            • 2017-01-23
            • 2015-01-20
            • 1970-01-01
            相关资源
            最近更新 更多