How to add a new line of text to an existing file in Java?

297,351

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

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) {}

Solution 5

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();
        }
    }
}
Share:
297,351
CompilingCyborg
Author by

CompilingCyborg

Compiling a Cyborg! ;D

Updated on July 16, 2022

Comments

  • CompilingCyborg
    CompilingCyborg almost 2 years

    I would like to append a new line to an existing file without erasing the current information of that file. In short, here is the methodology that I am using the current time:

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

    The problem with the above lines is simply they are erasing all the contents of my existing file then adding the new line text.

    I want to append some text at the end of the contents of a file without erasing or replacing anything.

  • CompilingCyborg
    CompilingCyborg over 13 years
    Thanks so much! Please is there a way to append ("\n") at the end after each output? As you know it is appending everything in one line ignoring my "\n" escapes!
  • Mario F
    Mario F over 13 years
    BufferedWriter has a newLine() method. You can use that, or use a PrintWriter instead, which provides a println() method
  • CompilingCyborg
    CompilingCyborg over 13 years
    Thanks! but for some bizarre reason when I am trying to use the: output.newLine() | does not exist within the list of methods. I am using NetBeans 6.9. All the other methods exist there. Do you know what might be the cause of that?
  • Mario F
    Mario F over 13 years
    yes, you are storing your output as a Writer, which is a smaller interface. You will have to explicitly store it as a BufferedWriter output if you want access to that method.
  • yegor256
    yegor256 almost 12 years
    Don't forget to close FileOutputStream
  • rpax
    rpax about 10 years
    \r\n is for windows. It's better use "line.separator" property
  • glider
    glider over 9 years
    This solution solve problem for append exist utf-8 file.
  • vkstream
    vkstream about 3 years
    BufferedWriter does not do any magic implicitly. You need to invoke newLine() method then only it does. See the complete code here. try(FileWriter fw=new FileWriter("/home/xxxx/playground/coivd_report_02-05-2021.tx‌​t",true); BufferedWriter bw= new BufferedWriter( fw)){ bw.newLine(); bw.append("When this COVID ends"); }catch (IOException exception){ System.out.println(exception); }