首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么File.exists()不起作用

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

Stack Overflow用户
提问于 2018-02-19 14:14:43
回答 1查看 486关注 0票数 0

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

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

代码语言:javascript
复制
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,但找不到我做错了什么。当我打印文件名时,会打印出完整的部署路径,如下所示

代码语言:javascript
复制
!@#!@# so difficult to be simple... vfs=$my_server_deployment_folder_location$/helloworld/watstheday.txt
EN

回答 1

Stack Overflow用户

发布于 2018-02-19 15:11:36

资源不是文件。当您进行开发(例如,在集成开发环境中)并且还没有打包应用程序时,您可能会得到实际文件的路径(在src/main/resources中的某个位置)。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48860434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档