This is finally , not finally() :
try { //... } catch(IOException e) { //... } finally { //... }
By the way, you have an infinite loop:
int c=fr.read(); while(c!=-1) { fw.write(c); }
You must read the data inside the loop to complete it:
int c=fr.read(); while(c!=-1) { fw.write(c); c = fr.read(); }
In the finally block, the variables fr and fw cannot be found because they are declared in the try scope. Declare them outside:
FileReader fr = null; FileWriter fw = null; try {
Now, since they are initialized to null , you should also do a null check before closing them:
finally { if (fr != null) { fr.close(); } if (fw != null) { fw.close(); } }
And the close method on both can throw an IOException , which should also be handled:
finally { if (fr != null) { try { fr.close(); } catch(IOException e) { //... } } if (fw != null) { try { fw.close(); } catch(IOException e) { //... } } }
In the end, since you don't want to have a lot of code to close the main thread, just move it to the method that processes Closeable (note that both FileReader and FileWriter implement this interface):
public static void close(Closeable stream) { try { if (stream != null) { stream.close(); } } catch(IOException e) {
In the end, your code should look like this:
import java.io.*; class FileDemo { public static void main(String args[]) { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("1.txt"); fw = new FileWriter("2.txt"); int c = fr.read(); while(c!=-1) { fw.write(c); c = fr.read(); } } catch(IOException e) { e.printStackTrace(); } finally { close(fr); close(fw); } } public static void close(Closeable stream) { try { if (stream != null) { stream.close(); } } catch(IOException e) {
Starting with Java 7, we have try-with-resources , so the code above can be rewritten like this:
import java.io.*; class FileDemo { public static void main(String args[]) {