When writing to a file with a BufferedWriter, the content is not directly written to disk, as it is obviously buffered. You should flush the content as @ludo_rj suggested in his answer.
Better yet is to close the writer as early as possible, which will automatically flush the content. Closing the reader is also necessary, by the way.
You should go with the following mechanism (I have distributed the approach into several methods to make it more clear):
public class SaveStateTesing {
private static final String FILE_NAME = "C:\\Users\\Nicolas\\Desktop\\save.txt";
public static void main(String[] args) throws IOException {
saveState("helloWorld", FILE_NAME);
String state = readState(FILE_NAME);
System.out.println(state);
}
private static void saveState(String state, String fileName) throws IOException {
try(PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(fileName)))) {
writer.println(state);
}
}
private static String readState(String fileName) throws IOException {
try(BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
return reader.readLine();
}
}
}
Note, that I used the try-with-resource statement, only available in Java 7 (and 8, of course). If you are running it in an older Java version, you must write the methods as following:
private static void saveState(String state, String fileName) throws IOException {
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
writer.println(state);
} finally {
if (writer != null)
writer.close();
}
}
private static String readState(String fileName) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
return reader.readLine();
} finally {
if (reader != null)
reader.close();
}
}