I am trying to copy the contents of one text file ("1.txt") which contains 2-3 integer numbers (ex: 1 2 3) to another text file ("2.txt") but I am getting the following error upon compilation
import java.io.*;
class FileDemo {
public static void main(String args[]) {
try {
FileReader fr=new FileReader("1.txt");
FileWriter fw=new FileWriter("2.txt");
int c=fr.read();
while(c!=-1) {
fw.write(c);
}
} catch(IOException e) {
System.out.println(e);
} finally() {
fr.close();
fw.close();
}
}
}
Command prompt:-
C:\Documents and Settings\Salman\Desktop>javac FileDemo.java
FileDemo.java:20: error: '{' expected
finally()
^
FileDemo.java:20: error: illegal start of expression
finally()
^
FileDemo.java:20: error: ';' expected
finally()
^
FileDemo.java:27: error: reached end of file while parsing
}
^
4 errors
But upon checking the code, I find that the finally() block is properly closed.
A
Finally
block shouldn't have the round parentheses.Try:
Try this code:
1.your code is not correct > finally block does not takes parenthesis ahead if it. 2.parenthesis always comes in front of methods only. 3.dear your Scope of FileReader and FileWrier objects are end with in the try blocks so you will get one more error in finally block that is fw not found and fr not found 4."throws IOEXception" also mention front of main function
It's
finally
, notfinally()
:By the way, you have an endless loop there:
You must read the data inside the loop in order to let it finish:
In the
finally
block, yourfr
andfw
variables can't be found since they're declared in the scope of thetry
block. Declare them outside:Now, since they are initialized with
null
value, you must also do anull
check before closing them:And the
close
method on both can throwIOException
that must be handled as well:In the end, since you don't want to have a lot of code to close a basic stream, just move it into a method that handles a
Closeable
(note that bothFileReader
andFileWriter
implements this interface):In the end, your code should look like:
Since Java 7, we have
try-with-resources
, so code above could be rewritten like:Its a compilation error