stud91
stud91

Reputation: 1854

Error in reading from file (Java)

I posted a similar question here: Read from a file containing integers - java but couldn't get a decent reply.

Now I have written this new code which only reads a file and outputs the result.

I get a FileNotFoundException whenever I try to read from a file. The code is below:

import java.io.*;

public class second {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

    File f = new File("C:\\Users\\Haroon\\workspace\\ppp\\temperature.txt");
    FileReader file = new FileReader(f);
    BufferedReader buf = new BufferedReader(file);

    String s = null;
    while((s = buf.readLine()) != null){
        System.out.println(s);
    }
}

}

This is strange because the file is in the project's folder. Any help would be appreciated.

Upvotes: 1

Views: 149

Answers (2)

dejavu
dejavu

Reputation: 3254

I don't know why you are unable to read the file. Its working fine on my system. Since you are making you project in eclipse. I will post a workaround here.

System.out.println(System.getProperty("user.dir"));

Use this command to find the current user directory at the time of execution. Now directly place the file in that user directory. Now you can directly read the file just by its name. For eg:

File f = new File("temperature.txt");

Also as mentioned by 'lxxx' do check the file name and the extension by enabling show file extension option in Windows.

Upvotes: 0

ixx
ixx

Reputation: 32267

That should work. Go to the location of the file, copy the path, paste it in your code, and escape the slashes. You are missing something.

Also check that the name/extension of the file is correct, you could have something like "temperature.txt.txt".

Upvotes: 3

Related Questions