简体   繁体   中英

Buffered Reader text file?

this is my first post on stack 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM