How to append text to an existing text file in Java

3 Answers

0 votes
package javaapplication1;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Example {
    
    public static void main(String[] args) {
       
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("d:/test.txt", true))) {
            bw.newLine();
            bw.write("append line 1");
            bw.write(" continue - same append line 1");
            bw.newLine();
            bw.write("append line 2");
            bw.flush();
        } catch (IOException ex) {
            Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
   
   
/*
run:

check d:\test.txt file
    
*/

 



answered Jan 23, 2016 by avibootz
edited Jan 24, 2016 by avibootz
0 votes
package javaapplication1;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Example {
    
    public static void main(String[] args) {
       
        try {
            Files.write(Paths.get("d:\\test.txt"), 
                                  "\r\nlast line".getBytes(), 
                                  StandardOpenOption.APPEND);
        } catch (IOException ex) {
            System.err.println("IOException: " + ex.getMessage());
        }
    }
}
   
   
/*
run:

check d:\test.txt file
    
*/
   
   
/*
run:

check d:\test.txt file
    
*/

 



answered Jan 23, 2016 by avibootz
edited Jan 24, 2016 by avibootz
0 votes
package javaapplication1;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Example {
    
    public static void main(String[] args) {
       
        try (PrintWriter pw = new PrintWriter(new BufferedWriter(
                                              new FileWriter("d:\\test.txt", true)))) {
            pw.println();
            pw.print("last line");
        } catch (IOException ex) {
            System.err.println("IOException: " + ex.getMessage());
        }
 
    }
}
   
   
/*
run:

check d:\test.txt file
    
*/

 



answered Jan 23, 2016 by avibootz
edited Jan 24, 2016 by avibootz

Related questions

1 answer 190 views
1 answer 181 views
1 answer 164 views
1 answer 190 views
1 answer 196 views
1 answer 192 views
...