java - 为什么 File.exists() 不起作用

标签 java file-io getresource

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

enter image description here

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

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

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

最佳答案

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

但是,当应用程序打包时,资源就是存档中的条目。它们不再作为文件存在。因此,请勿将 File 与资源一起使用。

关于java - 为什么 File.exists() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48860434/

相关文章:

java - 如何将 jasper 报告从 xalan 切换到 saxon?

haskell - haskell : how to force evaluation of functions and write to a file sequentially?

java - 覆盖 jar 文件中包含的资源

JAVA 为什么只有图像才能与 class.getResource 配合使用

java - 当 minifyEnabled 为 true 时 Android 应用程序崩溃

java - @Override注解怎么写

java - jps、jinfo、jstat、jmap、jstack是如何获取本地Java进程信息的?

c - 从文件 C 读取时状态访问冲突

java - BufferedReader 如何跟踪已读取的行?

java - 当尝试通过 jedis 连接器使用错误的 ip 连接 Redis 时,线程等待时间延长的原因是什么?