开发者

Converting Java URL to valid File path in Linux

Ok I'm developing in Linux using Eclipse a program that needs to read a text file. The idea is to have the JAR and text file on the same folder. So I'm getting the text file path like this:

Client.class.getClassLoader().getResource("Client.class");

This correctly returns the path and I append the file name and get the below path:

/home/marquinio/workspace/my_project/info.txt

Problem is when I export my project into an executable JAR file. The JAR can't read the file. I double checked and everything looks fine. The 开发者_运维技巧only problem I see is that now the path has some "file:" appended at the beginning like this:

file:/home/marquinio/workspace/my_project/info.txt

which is probably why I'm getting a "FileNotFoundException". The JAR and text file are both in the same folder.

Anyone knows how to fix this? Why would Java behave different between Eclipse and executing JAR in command prompt? Is there a replacement to the "...getResource(...)" provided by Java without that "file:"?

NOTE: this JAR should also be compatible in Windows environment. Still need to test it.

Thanks in advance.


The resource you are referring to is not guaranteed to be a file on the file system. Why not use ClassLoader#getResourceAsStream()? Without looking into the details, my best guess is that the different behavior you are seeing is because a different classloader is being used in each case above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜