-2

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)?

  • Your comment says "I can't copy the contents of the file". Why not? Do you get a compiler error? A run-time exception? Please post details (including any error messages or stack traces as applicable). – Ted Hopp May 07 '21 at 15:07
  • If you don't use try-with-resources, you need to take care of calling `close()` on the file handlers yourself. Try-with-resources is better: stick with that. – khelwood May 07 '21 at 15:08
  • @TedHopp No error is shown... The source2.txt will just be blank ... I thought there will be no point in putting a blank output. – Something Nice May 07 '21 at 15:12
  • @khelwood I just wanted to know what does it work with fileReader being outside of try block but not fileWriter – Something Nice May 07 '21 at 15:13
  • @SomethingNice Presumably because you didn't close the filewriter and some of what you tried to write was still cached. – khelwood May 07 '21 at 15:14
  • @SomethingNice It looks like you have not understood scopes and why try-resource-catch is used. Please look for examples, they will all clear it up. – JayC667 May 07 '21 at 15:16

2 Answers2

0

If you do not use try-with-resource you must close the resource yourself.
This can be necessary to have any cached data written to the stream (flush), e.g. writing to a file; also good to free system resources.


try (var resource = new Resource()) {
    // statements
}

is basically (ignoring error handling/exceptions) the same as:

var resource = new Resource();
// statements
resource.close();

or (a bit better)

var resource = new Resource();
try {
    // statements
} finally {
    resource.close();
}

This can get somehow complicated if error handling is added - so it is better to use try-with-resource (at the very least it makes the code much easier to read/understand/maintain).

  • This is correc. But this will point him in the wrong direction. So I do NOT support this. – JayC667 May 07 '21 at 15:15
  • f2.flush() works too. So, The content written will stay in Buffer and will not be flushed till f2.close() is called. If i want to bypass this then i can use f2.flush() without closing(Which is not recommended). – Something Nice May 07 '21 at 15:23
0

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.

  • Usually the call to `flush()` is unnecessary. The call to `close()` will make sure the output is flushed before the underlying output stream is closed. The only reason to call `flush()` just before calling `close()` is to separately handle any exceptions that may arise when flushing the stream. Such exceptions are swallowed when `close()` is called. – Ted Hopp May 07 '21 at 15:29