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

时间:2018-02-19 06:14:43

标签: java file-io getresource

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

enter image description here

我通过getResourceAsStream()的{​​{1}}方法读取文件,并在我的代码中执行进一步的操作,这些操作完美无缺。 但是,如果我尝试通过以下代码检查文件是否存在,则它总是返回false。

ClassLoader

我在最后提出这个问题之前咨询了following posts,但却找不到我做错了什么。当我打印文件名时,它将打印出显示为

的完整部署路径
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();
        }

1 个答案:

答案 0 :(得分:1)

资源不是文件。当您开发(例如,在IDE中)并且还没有打包应用程序时,您可能会获得真实文件的路径(ResponseEntity<Void> result = restTemplate.exchange(url, HttpMethod.POST, request, Void.class); 中的某个地方)。

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

相关问题