user3001408
user3001408

Reputation: 310

Cannot open file in java

I am trying to open a text file in java. I am using ubuntu 12.04. Following is my code:

package nlp;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;

public class sentence {

public static void main(String[] args) {
    System.out.println("hello");
    FileReader fr = new FileReader("test.txt");
    BufferedReader br = new BufferedReader(fr);

    String line;
    while ((line = br.readLine()) != null) {
        // process the line.
    }
    br.close();

}

}

I am using Eclipse for development. It says "FileNotFound". I have put the text file in .class as well as .java folder. Where am I going wrong?

Upvotes: 0

Views: 10209

Answers (4)

mahesh
mahesh

Reputation: 1331

The file should be in root of the project folder as given below. Your code is working fine.

eclipse workspace

Upvotes: 1

Teddy
Teddy

Reputation: 4223

As Arnaud mentioned try this to find where Java is expecting the file:

System.out.println(new File(".").getAbsolutePath());

Upvotes: 0

jeroen_de_schutter
jeroen_de_schutter

Reputation: 1883

The default execution directory in Eclipse is the root of the project folder. Put the file there or prefix the path with correct underlying folder structure.

Upvotes: 4

sriram
sriram

Reputation: 128

you need to put that in try-catch because it throws IOException which is checked Exception.Put the code in try-catch or handle the exception using "public static void main(String[] args) throws IOException"

Upvotes: 1

Related Questions