I’m trying to run this code taken from Sun Java site (I didn’t copy it, Looked at it and wrote it as it would help me to remember the code).
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharEx{
FileReader inputStream = null;
FileWriter outputStream = null;
public static void main(String args[]) throws IOException{
FileReader inputStream = null;
FileWriter outputStream = null;
try{
inputStream = FileReader("xanadu.txt");
outputStream = FileWriter("out.txt");
int c;
while ((c = inputStream.read()) != -1){
outputStream(c);
}
}
finally{
if(inputStream !=null){
inputStream.close();
}
if(outputStream !=null){
outputStream.close();
}
}
}
}
But I’m getting follwing error.
D:\Java>javac CharEx.java
CharEx.java:14: cannot find symbol
symbol : method FileReader(java.lang.String)
location: class CharEx
inputStream = FileReader("xanadu.txt");
^
CharEx.java:15: cannot find symbol
symbol : method FileWriter(java.lang.String)
location: class CharEx
outputStream = FileWriter("out.txt");
^
CharEx.java:18: cannot find symbol
symbol : method outputStream(int)
location: class CharEx
outputStream(c);
^
3 errors
From the message I think that the system is looking for FileReader inside java.lang whereas it should look for it inside java.io.* :((
Can someone help me where I’m getting wrong?
PS: I’m on JDK 1.5.
You’re trying to instantiate a
FileReaderand aFileWriter(i.e. create objects of those types).To do that you need to use the
newkeyword:By leaving out the
newthe code looks like a method call, so the compiler looks for a method namedFileReader(andFileWriter) and doesn’t find it, which it tells you in a somewhat strange, but surprisingly clear language.Hint: “symbol” is what a compiler calls a “name”. That name can be of a class, method, variables, … The exact problem can be found when checking the “symbol: “line. It tells you that the compiler looks for a method called
FileReaderthat takes aStringparameter: