如何添加一个新的行文本到现有的文件在 Java?

我想添加一个新的行到一个现有的文件,而不删除该文件的当前信息。简而言之,以下是我目前使用的方法:

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

上面几行的问题很简单,它们删除了现有文件的所有内容,然后添加新的行文本。

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

319368 次浏览

you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append) constructor.

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

should do the trick

On line 2 change new FileWriter(my_file_name) to new FileWriter(my_file_name, true) so you're appending to the file rather than overwriting.

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

You can use the FileWriter(String fileName, boolean append) constructor if you want to append data to file.

Change your code to this:

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

From FileWriter javadoc:

Constructs a FileWriter object given a file name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

The solution with FileWriter is working, however you have no possibility to specify output encoding then, in which case the default encoding for machine will be used, and this is usually not UTF-8!

So at best use FileOutputStream:

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

Try: "\r\n"

Java 7 example:

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

In case you are looking for a cut and paste method that creates and writes to a file, here's one I wrote that just takes a String input. Remove 'true' from PrintWriter if you want to overwrite the file each time.

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

Starting from Java 7:

Define a path and the String containing the line separator at the beginning:

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

and then you can use one of the following approaches:

  1. Using Files.write (small files):

    try {
    Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
    System.err.println(e);
    }
    
  2. Using Files.newBufferedWriter(text files):

    try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
    writer.write(s);
    } catch (IOException ioe) {
    System.err.format("IOException: %s%n", ioe);
    }
    
  3. Using Files.newOutputStream (interoperable with java.io APIs):

    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
    out.write(s.getBytes());
    } catch (IOException e) {
    System.err.println(e);
    }
    
  4. Using Files.newByteChannel (random access files):

    try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
    sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
    System.err.println(e);
    }
    
  5. Using FileChannel.open (random access files):

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

Details about these methods can be found in the Oracle's tutorial.