I do not understand why writing to the file does not occur if the stream’s close method has not been called. That is, this code does not write to the file:

public class Solution { public static void main(String[] args) throws IOException { BufferedReader file1 = new BufferedReader(new FileReader(args[0])); FileWriter file2 = new FileWriter(args[1]); String line; while ((line = file1.readLine()) != null) { String[] words = line.split(" "); for (int i = 0; i < words.length; i++) { if (words[i].toCharArray().length > 6) { file2.write(words[i] + ","); } } } } } 

But if you add it there, then everything works:

 file1.close(); file2.close(); 

I understand that in close() flush is called, but does the thread really not close after the program ends? How it works ?

    1 answer 1

    Each call to the write() method of the FileWriter class converts characters into a sequence of bytes. The bytes received fall into a buffer, the size of which is chosen by default as large as possible in order to ensure physical writing by large data blocks, reducing the number of disk accesses.

    Until the buffer is filled, or the stream is not closed, or the flush() method is not explicitly called, no entry will be made. JVM does not guarantee the automatic closure of threads when an application terminates. A good option would be to use try-with-resources .