如何在Java中向现有文件添加新行文本?

Com*_*org 80 java file-io text-processing

我想在不删除该文件的当前信息的情况下将新行附加到现有文件.简而言之,这是我使用当前时间的方法:

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();
Run Code Online (Sandbox Code Playgroud)

上述行的问题只是它们删除了我现有文件的所有内容,然后添加了新的行文本.

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

Mar*_*o F 117

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

output = new BufferedWriter(new FileWriter(my_file_name, true));
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩

  • `BufferedWriter`有一个`newLine()`方法.您可以使用它,或者使用`PrintWriter`代替它,它提供了`println()`方法 (9认同)
  • 是的,你将`output`存储为`Writer`,这是一个较小的接口.如果要访问该方法,则必须将其显式存储为"BufferedWriter输出". (6认同)
  • 非常感谢!请问有没有办法在每次输出结束后追加("\n")?如你所知,它将所有内容添加到一行中而忽略了我的"\n"转义! (2认同)
  • 谢谢!但是当我尝试使用:output.newLine()|时出于某些奇怪的原因 在方法列表中不存在.我正在使用NetBeans 6.9.那里存在所有其他方法.你知道这可能是什么原因吗? (2认同)

Dan*_*lor 25

解决方案FileWriter是有效的,但是你没有可能指定输出编码,在这种情况下将使用机器的默认编码,这通常不是UTF-8!

所以最好使用FileOutputStream:

    Writer writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(file, true), "UTF-8"));
Run Code Online (Sandbox Code Playgroud)


Sto*_*fkn 13

试试:" \ 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) {}
Run Code Online (Sandbox Code Playgroud)

  • \ r \n适用于Windows.最好使用"line.separator"属性 (4认同)

ROM*_*eer 11

Java 7开始:

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

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

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

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

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

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

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

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

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

有关这些方法的详细信息,请参阅Oracle教程.


小智 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());
        }
Run Code Online (Sandbox Code Playgroud)


Mat*_*ttC 5

如果您正在寻找一种创建并写入文件的剪切和粘贴方法,那么我写的这种方法只需要一个String输入。如果您想每次覆盖文件,请从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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)