Zeus
Zeus

Reputation: 2253

Reading a .txt file in a project in Eclipse

Well I understand that this question has been asked multiple times, but despite following all the advice in those links I still end up getting file not found error.

These are the links I've already checked.

Where do I put the txt file that I want to read in Java?

How to really read text file from classpath in Java

So please don't get trigger happy marking it as duplicate.

For one most of these links seem to use the word ClassPath and BuildPath interchangeably, are they the one and the same thing, coz in my IDE I can't seem to find anything related to ClassPath, it's only BuildPath.

So this is my directory structure.

enter image description here

The caller class needs the file

enter image description here

Well I've tried pretty much everything in the links and I still can't read the file.

The code that reads the file is here

String path = "DataSource/data1.txt";
        String jsonData = null;

        try {

            jsonData = Reader.readFile(path);
        } catch (Exception e) {
            e.printStackTrace();
        }

Any help appreciated.

Upvotes: 0

Views: 5463

Answers (2)

Mahendra
Mahendra

Reputation: 1426

Term ClassPath related to java code compilation and execution while term BuildPath related to IDE (i.e. Eclipse). IDE adds libraries, which are added to BuildPath, automatically to the ClassPath while building and running the application/program.

"The caller class needs the file", then you can provide the file-path in two way

  1. Provide the absolute file path.
  2. Provide relative path, which you are doing, but make sure it is relative to the current location from where you are running your program. In case of IDE relative path should be from Project-Directory.

Upvotes: 0

Sombriks
Sombriks

Reputation: 3622

try

String path = "src/main/java/DataSource/data1.txt";

understand that your execution point inside eclipe is at project root.

However you might want to package such resource on your jar. if so, you'll need to use something like:

jsonData = Reader.readFile(Caller.class.getResourceAsStream("DataSource/data1.txt""));

At last, move the .txt file to 'src/main/resources', since it's a good practice.

Upvotes: 2

Related Questions