When you work with a buffer, always use flush(), as it forces the data from the buffer to be written to the final destination. Not using flush on a buffer can cause the data not to be written to your file.
public void writeToFile(String fullpath, String contents) {
// Paths AṔI
Path filePath = Paths.get(fullpath, "contents.txt");
try {
// Files AṔI
Files.createDirectories(filePath.getParent());
} catch (IOException e) {
e.printStackTrace();
return;
}
// Files AṔI
try (BufferedWriter bw = Files.newBufferedWriter(filePath)) {
bw.write(contents);
bw.flush(); // <<--- Flush force write in file
} catch (IOException e) {
e.printStackTrace();
}
}
When working with files in Java, use the Paths and Files APIs.
This way, you don't need to worry about operating system issues.
BufferedWriter) because it ensures that the data in memory is actually written to the file.Reference: