简体   繁体   English

用Java的getResource找不到文件

[英]File not found with Java's getResource

I am trying to load a file called Test from my class, but somehow Java says, that the file does not exist, while it clearly does and neither the URL object url is null nor does it contain an invalid path and when I debug the program, the File object file has the right path stored in it. 我正在尝试从我的类加载一个名为Test的文件,但是Java不知何故说该文件不存在,尽管它显然存在,并且URL对象url都不为null,也不包含无效路径,并且在调试程序时,文件对象file中存储了正确的路径。 When I print out file.getPath() and paste it into the Windows Explorer it opens up just fine. 当我打印出file.getPath()并将其粘贴到Windows资源管理器中时,它打开就好了。 I am running Eclipse, but I tried running the program in a console and it doesn't work either. 我正在运行Eclipse,但是我尝试在控制台中运行该程序,但它也不起作用。

public static void main(String[] args) {
    URL url = Test.class.getResource("/Test");
    File file = new File(url.toExternalForm());

    if (!file .exists()) {
      System.out.println("File does not exist: " + file.getPath());
      System.exit(-1);
    }
}

I tried it with getResource("Test") , File("Test") and File("/Test") as well, but that didn't work either. 我也尝试了getResource("Test")File("Test")File("/Test") ,但是那也不起作用。 I don't know why this happens know, since I work often with files and never had a problem. 我不知道为什么会这样,因为我经常使用文件并且从未遇到过问题。

The file I want to load is located in a source folder and yes, I checked, it is recognized as a source folder in Eclipse and is in the classpath. 我要加载的文件位于源文件夹中,是的,我检查了一下,它在Eclipse中被识别为源文件夹,并且在类路径中。 By the way the file is actually just called Test without an extension. 顺便说该文件实际上只是被称为Test没有扩展名。

Bin folder: Bin文件夹:

bin/
  |___package/Test.class
  |___Test

Output (Project is called "Other"): 输出(项目称为“其他”):

File does not exist: file:\F:\Development\CoolDirectory\Other\bin\Test

Using Test.class.getResource("/Test"); 使用Test.class.getResource("/Test"); can cause a lot of trouble as you never know if the resource is a plain file or inside a JAR file are somehow not directly accessible. 可能会造成很多麻烦,因为您永远不知道无法以某种方式直接访问资源是纯文件还是JAR文件。

Therefore the preferred way is to use getResourceAsStream(String) which returns an InputStream you can directly read from. 因此,首选方法是使用getResourceAsStream(String) ,该方法返回可以直接读取的InputStream。

The following example used Java 9+ featured: 以下示例使用了Java 9+功能:

    byte[] data = null;
    try (InputStream in = Test.class.getResourceAsStream("/Test")) {
        if (in == null) {
            System.out.println("Resource '/Test' does not exist");
            System.exit(-1);
        }
        data = in.readAllBytes();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM