user3841581 user3841581 - 1 month ago 6
Java Question

How to Write to line by line in a single file on different methods in java

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.

Answer

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

Comments