开发者

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

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 "开发者_StackOverflow社区../resources/file.txt". However I am getting an error saying that the file does not exist.

Any help would be appreciated thanks!


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();
    }
}


Files will be referenced relative to your project path, so use "resources/file.txt" to reference the file.

However, if you want the file to be accessible when you export the program as a JAR, the path "resources/file.txt" must exist relative to your JAR.


It depends on how you have specified your Java Build Path inside eclipse. I have tested two setups with different results:

  1. Define the directory working/src only as build path. You can get the information what is in your build path through: Select project > Properties > Java Build Path > Tab Source. There are all source folders listed. You see there that there is a default output folder defined. All resources that are contained in a build path are copied to the default output folder, and are then available for the eclipse classes there. You can check that in the resource perspective in your bin folder if the resource is copied there. In this setup, only the classes are generated, resources are not copied (and therefore not found).
  2. Define the directory working/src and resources as build path. Then the resource is copied and may then found by the path "file.txt"

So eclipse has a simple build process included and hides that from the developer, but it is a build process nonetheless.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜