-1

I am trying to open a txt file in a java program and the compiler keeps advice me throwing the error, that is responsible for the program crash:

FileNotFoundException

I am working on intelliJ and the file is in the same directory I am working on, it is in the src directory.

The file is called dataset.txt and I tried all of the below formats to solve the issue.

BufferedReader br = new BufferedReader(new FileReader("D:\\Mhamed\\Courses\\Algorithms Specialization\\Course 1\\Week 2\\src\\dataset.txt"));

BufferedReader br = new BufferedReader(new FileReader("dataset.txt"));

BufferedReader br = new BufferedReader(new FileReader("/dataset.txt"));

BufferedReader br = new BufferedReader(new FileReader("./dataset.txt"));

BufferedReader br = new BufferedReader(new FileReader("src\\dataset.txt"));

BufferedReader br = new BufferedReader(new FileReader("D:/Mhamed/Courses/Algorithms Specialization/Course 1/Week 2/src/dataset.txt"));

Finally, nothing works and I don't know what is the issue. Can someone help me?

xKobalt
  • 1,498
  • 2
  • 13
  • 19
  • 1
    We love that you're here and we can't reproduce your problem with the code you provided. One thing you might do is add code to *write* to a new file and see that the default folder is, then adjust your read logic accordingly. – nicomp Jul 17 '20 at 14:57
  • The src directory is the worst place to put a text file into. Unless you really want to have it in the classpath. In that case you would access it via the classloader. And the src directory is usually *not* the working directory. The default working dir is the project dir. You can change it in your run configuration. To find out the absolute path you can use something like that `System.out.println(new File("dataset.txt").getAbsolutePath());` – vanje Jul 17 '20 at 15:25

1 Answers1

0

Make sure to put the file in the resources folder, that way you can use:

InputStream in = Reader.class.getClassLoader().getResourceAsStream("dataset.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));   //read file
int lines = 0;     
while (br.readLine() != null) lines++;         //example to count lines

You then can apply code to every line of the file.

Hannes
  • 93
  • 5