Eclipse how to reference file in a different src under the same project

jason picture jason · Sep 9, 2011 · Viewed 11.6k times · Source

My current setup in eclipse is like this:

trunk
--working/src
--resources

I have a java file inside a package under working/src and I am trying to retrieve a file in the resources. The path I am using is "../resources/file.txt". However I am getting an error saying that the file does not exist.

Any help would be appreciated thanks!

Answer

Surendra Jnawali picture Surendra Jnawali · Jan 15, 2013

Considering your structure

I have package like

trunk

  • working/src/FileRead.java
  • resources/name list.txt

Following Code might solve your problem

 package working.src;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class FileRead {
    public FileRead() {
        URL url = getClass().getResource("/resources/name list.txt");
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String nameList;
            while ((nameList = in.readLine()) != null) {
                System.out.println(nameList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new FileRead();
    }
}