0

I would like to write in a single file in java but in different methods. I wrote this

import java.io.*;
public class Test {
  public static File file = new File("text.log");


  public static void main (String [] args) throws IOException
  {
    FileWriter input= new FileWriter(file);
    input.write("hello");
    input.write("\n");
    input.close();
    test();
   }

  public  static void test() throws IOException
   {

    FileWriter input= new FileWriter(file);
    input.write("world");
    input.write("\n");
    input.close();
   }


}

The output is just world. It looks like calling the function test() overwrites what was previously written.

user3841581
  • 2,637
  • 11
  • 47
  • 72
  • Others have mentioned append mode, but why not make the `FileWriter` itself a class variable and open it only once? – Frank Puffer Oct 29 '16 at 11:13
  • The real lesson here is: study the documentation for the classes you are using! That is the essence of programming: when you start using a new library class, you **first** study it to understand how it works and what it is doing for you! – GhostCat Oct 29 '16 at 11:22

2 Answers2

3

You need to open the FileWriter in append mode by passing true as the second argument:

public static File file = new File("text.log", true);

From the Javadoc:

public FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I assume you mean FileWriter = new FileWriter(file, true); because when I put wja you just mentioned on my code, It says that I can not resolve "java.lang.String, boolean – user3841581 Oct 29 '16 at 11:20
  • @user3841581 The Javadoc clearly mentions a constructor which takes a boolean and string. – Tim Biegeleisen Oct 29 '16 at 11:23
1

When you write new FileWriter(file, true), it will append instead of overwrite.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121