I want to check if a file exists on resources and use this line:
getClass().getResource(resource.getResourceFullName()) != null
resource.getResourceFullName()
is a method that returns just the file name without slashes like testevnvariables.yaml
I got that file did not exist. For your information, I use Windows and IntelliJ IDEA locally but prod is on Linux.
Then I tried to do this, but, again, the file does not exist:
getClass().getResource(File.separator resource.getResourceFullName()) != null
and only when I added manually "/" I got "exists":
getClass().getResource("/" resource.getResourceFullName()) != null
So my question is why it is happening? As far as I know, the default separator for Linux is slash, and for Windows is a backslash. File.separator returns a correct value for Windows - backslash but Java can't find it. I don't want to add "/" manually and want to be independent of the system and use something like System.lineSeparator() but for files. How can I do it?
I also tried to use File.exists()
but with the same result.
And why when I found a file, Idea shows me this path (with slashes like on Linux):
.../target/test-classes/testevnvariables.yaml
CodePudding user response:
A resource is something on the class path, which can be considered a sort of JVM specific virtual file-system (it is comprised of all JARs and directories, etc that have been specified on the class path). The file separator for this virtual file system is exclusively /
. So, just use /
and you are good to go. You don't need to fiddle with File.separator
or anything, as the /
is already system independent.
As an aside, even on Windows, most filesystem APIs allow you to use /
and \
interchangeably.