Skip to content
Advertisement

Why can’t I write FileWriter outside of Try with resources?

So, I just wanted to create a program to copy the contents from one file(source1) to another file(source2) and convert it into lowercase… while doing so i have came up with the code as:

        try(FileWriter fr=new FileWriter("Source1.txt")){
            String str="UPPER CASE";
            fr.write(str);
        }


        File file=new File("Source1.txt");
        //FileReader fr=new FileReader("Source1.txt"); // (1)
        //FileWriter f2=new FileWriter("Source2.txt"); // (2)

        try(FileReader fr=new FileReader("Source1.txt");FileWriter f2=new FileWriter("Source2.txt")){ //If i remove 
//file Reader from here and uncomment (1) the code works fine but if i do so with FileWriter (Remove
//fileWriter from here and uncomment (2)) I can't copy the contents of the file (No error is shown... the code executes but Source2.txt just comes out as blank file.


            char x[]=new char[(int)file.length()];
            fr.read(x);
            String str=new String(x);
            System.out.println(str);
            String st=str.toLowerCase();
            f2.write(st);


        }

Nothings wrong with the code but i just wanted to know why does it work this way(please read the comment in the code)?

Advertisement

Answer

If the writer is out of try-with-resources, you need to take care of flushing and closing the writer using

f2.flush()
f2.close()

flush() flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, it writes them immediately to their intended destination.

Try-with-resources does the same implicitly.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement