-3

I have a filewriter that takes String data from the user and writes it on the file. But the filewriter replaces the already existing data in that file. How do I prevent it from doing it? I just want to keep adding information without writing over something.

Here is the code

    String info = scan.nextLine();
    File myFile = new File ("/home/greg/workspace/Mavericks/fred.txt");
    FileWriter writer = new FileWriter (myFile);
    writer.write(register);
    writer.flush();

Thanks. I fixed that. Now I just want to make the writer write using spaces. When I write to the file it just keeps writing within the same line.

user207421
  • 305,947
  • 44
  • 307
  • 483
Kharbora
  • 85
  • 1
  • 2
  • 10

6 Answers6

1

Use second parameter of FileWriter, which is defining if you want to append or not. Just set it to true.

BufferedWriter writer = new BufferedWriter(new FileWriter(
                sFileName, true));

Add \n after each line.

Ondrej Tokar
  • 4,898
  • 8
  • 53
  • 103
1

You need use the boolean value true. From docs

public FileWriter(String fileName,
          boolean append)
           throws IOException

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

Parameters:

fileName - String The system-dependent filename.

append - boolean if true, then data will be written to the end of the file rather than the beginning.

Santhosh
  • 8,181
  • 4
  • 29
  • 56
0

Use

new FileWriter(myFile, true)

The second parameter is for appending.

DeiAndrei
  • 947
  • 6
  • 16
0

Api:

FileWriter(File file, boolean append)

Constructs a FileWriter object given a File object.

http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

Beri
  • 11,470
  • 4
  • 35
  • 57
0

FileWriter has an optional boolean in the constructor, which declares if it should be appended or not.

FileWriter writer = new FileWriter(..., true)
Terry Storm
  • 497
  • 3
  • 14
-1

BufferedWriter bw = new BufferedWriter(new FileWriter(filename ,true));

Prashant
  • 1
  • 4