Error when trying to compile the program
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 = 开发者_Python百科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 FileReader
and a FileWriter
(i.e. create objects of those types).
To do that you need to use the new
keyword:
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("out.txt");
By leaving out the new
the code looks like a method call, so the compiler looks for a method named FileReader
(and FileWriter
) 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 FileReader
that takes a String
parameter:
CharEx.java:14: cannot find symbol symbol : method FileReader(java.lang.String)
You are missing the new
keyword when initializing the reader and writer.
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("out.txt");
You are also missing something on this line:
outputStream(c);
Do you want to write to the output stream there? Then you should try this:
outputStream.write(c);
精彩评论