0
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class test3 {
        public static void main(String[] args) {

                //write
                try {
                        FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt");
                        PrintWriter pw = new PrintWriter (fw);

                        pw.println("This is just some test data");

                        pw.close();
                }
                catch (IOException e){
                        System.out.println("Error!");
                }

                //read
                try {
                        FileReader fr = new FileReader("C:\\Users\\Danny\\Desktop\\Credits.txt");
                        BufferedReader br = new BufferedReader (fr);

                        String str;

                        while ((str = br.readLine()) != null ) {
                                System.out.println(str + "\n");
                        }
                        br.close();            

                }
                catch (IOException e){
                        System.out.println("File not found!");
                }

        }
}

This works but over writes the text file each time with the new input. How do I stop this over writing so that all information is stored in the file like an archive.

3 Answers3

5

Pass true to your FileWriter like this -

FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt",true);

The second parameter to the FileWriter constructor will tell it to append to the file.

Docs --> http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,boolean)

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0

Open the file in Append mode the next time you want to write to file.

FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt",true);
Vivek Keshri
  • 108
  • 10
0

Use:

Files.newBufferedWriter(Paths.get("yourfile"), StandardCharsets.UTF_8,
    StandardOpenOption.APPEND);
fge
  • 119,121
  • 33
  • 254
  • 329