Question:

Help with a basic java question please?

by  |  earlier

0 LIKES UnLike

Hi,

I’m hoping someone can help with a basic java question on reading a txt file on Windows. I’ve managed to write the txt file and am now trying to read it using the following method (where findPath is a method to get the url using java.net.URL url = getClass().getResource(testFile.txt);:-

public void readFromFile(String inFile)

{

FileReader fileReader;

BufferedReader reader;

String data;

try

{

fileReader = new FileReader(findPath(inFile));

reader = new BufferedReader(fileReader);

data = reader.readLine();

while (data != null)

{

System.out.println(data);

data = reader.readLine();

}

reader.close();

}

catch (IOException e)

{

System.out.println("Error in reading from file. " + e);

}

}

I’m getting an exception error telling me the file cannot be found giving the missing file details as:-

C:\Documents%20and%20Settings\My%20Doc... (The system cannot find the path specified)

The file does exist in this path, so why can’t my method find it? Is it something to do with my set up, or is it something else.

Thanks for your help in advance.

 Tags:

   Report

2 ANSWERS


  1. your code is a little off, it should be similar to the following:

    BufferedReader input =  new BufferedReader(new FileReader(inFile));

    String data = null;

    try {

       while (( data = input.readLine()) != null){

              System.out.println(data);

            }

    } finally {

       input.close();

    } catch (IOException e) {

       e.printStackTrace();

    }

    ...

    personally i like to use the Scanner class. also, make sure you import java.io.*


  2. Why are you using the getResource() method from the class Class?  

    I'll assume that you are dealing with a "multiple class-loader" environment, such as maybe your application classes and other resources (like testFile.txt) are bundled in a JAR file.  

    In that case, the easier solution is to use getResourceAsStream("/testFile.txt").  

    This returns an InputStream that you can use directly.  The problem with getting a URL is that you have to be careful with encoding differences.  Notice that the file path you got in your application has those "%20"s?  Those are URL encoded blank spaces.  Those work fine when dealing with URLs, but do NOT work when dealing with file paths!

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions