amine amine - 2 months ago 8
Java Question

Not printing to file java

I am trying to log what my program is doing. Currently I'm using PrintWriter but all it produces is a blank txt file. Can someone please correct my code if possible or give any suggestions.

public class Log {
public static void log(String string){
if(string != null) {
System.out.println("log ".concat(string));
try {
PrintWriter out=new PrintWriter(new FileWriter("log.txt"));
out.println("log ".concat(string));
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void log(String[] strings) {
if (strings == null) return;
for(String string : strings) {
if (string != null) {
System.out.println("log ".concat(string));
try {
PrintWriter out=new PrintWriter(new FileWriter("log.txt"));
out.println("log ".concat(string));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Answer

You have to flush the PrintWriter to get data written in the file

PrintWriter out = new PrintWriter(new FileWriter("log.txt"));
out.println("log ".concat(string));
out.flush();

If you're done with writing into file you should close the PrintWriter which will also cause data to be written

out.close();