问题
I have a file watstheday.txt
in my src/main/resources
folder of my project as shown in the image file below.
I read the file through a getResourceAsStream()
method of the ClassLoader
and perform further actions in my code which is working perfectly.
However if I try to perform a check if the file exists through the below code it always returns 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();
}
I consulted the following posts before finally putting up this Question but couldn’t find what am I doing wrong. When I print the file name it gets printed with the complete deployment path shown as
!@#!@# so difficult to be simple... vfs=$my_server_deployment_folder_location$/helloworld/watstheday.txt
回答1:
Resources are not files. When you develop (say, in an IDE) and haven't packaged the application yet, you may get paths of real files (somewhere in src/main/resources
).
However when the application is packaged, resources are entries in an archive. They do not exist as files anymore. So do not use File
with resources.
来源:https://stackoverflow.com/questions/48860434/why-file-exists-does-not-work