1

I'm trying to learn how to use read line by line from a text file. Even though I put the txt file in the same src, the console always shows the error as - No such file or directory.

public class ddd {

public static void main(String[] args) {
    FileInputStream fis = null;
    BufferedReader reader = null;
    try {
        fis = new FileInputStream("/dd/src/com/dd/input.txt");
        reader = new BufferedReader(new InputStreamReader(fis));
        System.out
                .println("Reading File line by line using BufferedReader");
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            reader.close();
            fis.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }
}

}enter image description here

1
  • I might recommend using the current working directory System.getProperty("user.dir")) to find out where you are currently working. That proved to be one of the biggest issues I had when learning to use file input/output. Commented Jul 7, 2015 at 16:34

2 Answers 2

6

The problem is probably here:

"/dd/src/com/dd/input.txt"

On Linux at least, this would be an absolute path. What you probably want instead is a path relative to the project root:

"src/com/dd/input.txt"

Or, if you're packaging this file into your program, use a resource stream instead of a raw FileInputStream:

InputStream is = ddd.class.getResourceAsStream("input.txt");
Sign up to request clarification or add additional context in comments.

Comments

1

You need to use relative path e.g. "src/com/dd/input.txt". I tried and it's working fine.

Output

Reading File line by line using BufferedReader
hhhh

My input.txt has hhhh content.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.