this is my first post on st开发者_StackOverflow中文版ack overflow! I'm new to Java and I've recently been experimenting with the Java Buffered Reader for File I/O. I'm getting an exception
Exception in thread "main" java.io.FileNotFoundException
Here is a sample of my code:
System.out.println("Please input an existing filename, otherwise type in 0;");
fileName = input.nextLine();
if(fileName.compareTo("0") != 0)
{
BufferedReader inFile = new BufferedReader(new FileReader( fileName ) );
firstName = inFile.readLine();
lastName = inFile.readLine();
phoneNumber = inFile.readLine();
while (phoneNumber != null) {
c1[index] = new Contact(firstName,lastName,phoneNumber);
index++;
firstName = inFile.readLine();
lastName = inFile.readLine();
phoneNumber = inFile.readLine();
}
inFile.close();
}
I've placed my txt file where the .class and .java files are (I'm using the Netbeans IDE). And I type in "namelist.txt" as input for the fileName string.
Am I placing it in the wrong area or am I missing something?
Java can not find the file what you specify in fileName
fileName = input.nextLine();
add the following after fileName = input.nextLine();:
System.out.println("Reading from: " + new java.io.File( fileName ).getAbsolutePath());
to print out where java tries to locate your file
Use getClass().getResourceAsStream(filename) - this will resolve the filename relative to the current class location (within the classpath). Thus you will obtain an InputStream. Then wrap it in an InputStreamReader, specifying the desired encoding.
When you pass a filename it will be looked for in a default directory which you most likely don't want.
加载中,请稍侯......
精彩评论