【问题标题】:Why File.exists() does not work为什么 File.exists() 不起作用
【发布时间】:2018-07-29 08:23:41
【问题描述】:

我的项目的src/main/resources 文件夹中有一个文件watstheday.txt,如下图所示。

我通过ClassLoadergetResourceAsStream() 方法读取了文件,并在我的代码中执行了进一步的操作,该代码运行良好。 但是,如果我尝试通过以下代码检查文件是否存在,它总是返回 false。

try {
            ClassLoader classLoader = getClass().getClassLoader();
            System.out.println("!@#!@# so difficult to be simple..."+classLoader.getResource("watstheday.txt"));
            //this returns false but the file is there
            System.out.println("@#@ vertigo2 "+new File(classLoader.getResource("watstheday.txt").getFile()).isFile());
            //this ALSO returns false but the file is there
            System.out.println("@#@ vertigo2 "+new File(classLoader.getResource("watstheday.txt").getFile()).exists());
            //Giving the / to mark the root of the application though that's not required
            System.out.println("@#@ vertigo3 "+new File(classLoader.getResource("//watstheday.txt").getFile()).isFile());
            //the below code with getResourceAsStream works absolutely fine and i can read the file
            classLoader.getResourceAsStream("watstheday.txt");
            BufferedReader buf = new BufferedReader(
                    new InputStreamReader(classLoader.getResourceAsStream("watstheday.txt")));
            while (true) {
                lineJustFetched = buf.readLine();
                System.out.println(" @@#@ lineJustFetched =" + lineJustFetched);
            }
            buf.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

我在最终提出这个问题之前咨询了followingposts,但找不到我做错了什么。当我打印文件名时,它会打印出完整的部署路径,显示为

!@#!@# so difficult to be simple... vfs=$my_server_deployment_folder_location$/helloworld/watstheday.txt

【问题讨论】:

  • 您的文件是否可能存在于 zip 文件中?
  • 仅供参考,我在我的 Eclipse 上测试了你的代码并得到了@#@ vertigo2 true @#@ vertigo2 true
  • 阅读这篇文章,这解释了为什么getResource(...).getFile() 没有返回可以传递给java.io.File 构造函数的东西,因为它不是一回事:What's the difference between a Resource, URI, URL, Path and File in Java?
  • File.exists() 如果您的文件作为实体物理存在,则返回 true。在虚拟文件系统上时它总是返回 false。
  • @EvgeniyDorofeev 我反复尝试过,但对我来说不是这样。我看不到自己的愚蠢,????

标签: java file-io getresource


【解决方案1】:

资源不是文件。当您开发(例如,在 IDE 中)并且尚未打包应用程序时,您可能会获得真实文件的路径(在 src/main/resources 的某个位置)。

但是,在打包应用程序时,资源是存档中的条目。它们不再作为文件存在。所以不要在资源中使用File

【讨论】:

  • 文件被用作资源是一个非常常见的用例。就我而言,我已按照 maven 的说法将文件保存在资源文件夹中,并且能够通过 getResourceAsStream() 访问该文件以进行读取操作。只有 classLoader.getResource("watstheday.txt").getFile()).exists() 失败!
  • 我写过使用资源作为文件,而不是文件作为资源。
猜你喜欢
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多