File paths in Java (Linux)

2020-07-17 14:29发布

I have created a Java application that loads some configurations from a file conf.properties which is placed in src/ folder.

When I run this application on Windows, it works perfectly. However when I try to run it on Linux, it throws this error:

java.io.FileNotFoundException: src/conf.properties (No such file or directory)

9条回答
SAY GOODBYE
2楼-- · 2020-07-17 15:03

check your slashes and colons in my case i set my PS1 to following value

PS1='\n[\e[1;32m]$SYSNAME(\u)@[\e[1;33m]\w [\e[1;36m](\d \T) [!]\e[0m]\n\$ '

i am trying to read from the env .such as system.getenv

Java was throwing exception

java.lang.IllegalArgumentException: Malformed \uxxxx encoding

查看更多
闹够了就滚
3楼-- · 2020-07-17 15:10

What you want to do is check out System.getProperties() and look for file.separator. The static File.pathSeprator will also get you there.

This will allow you to build a path that is native for whatever system you're running on.

(If indeed that is the problem. Sometimes I like to get the current directory just to make sure the directory I think I'm running in is the directory I'm really running in.)

查看更多
Root(大扎)
4楼-- · 2020-07-17 15:11

Try the double slash, after doing things in JBoss I often had to refactor my code to use the double slashes

查看更多
男人必须洒脱
5楼-- · 2020-07-17 15:14

Instead of

String PROP_FILENAME="src/conf.properties";

use

String PROP_FILENAME="src" + File.separator + "conf.properties";

Check the API for more detail: http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html

查看更多
小情绪 Triste *
6楼-- · 2020-07-17 15:18

If you've packaged your application to a jar file, which in turn contains the properties file, you should use the method below. This is the standard way when distributing Java-programs.

URL pUrl = this.getClass().getResource("/path/in/jar/to/file.properties");

Properties p = new Properties();
p.load(pUrl.openStream());

The / in the path points to the root directory in the jar file.

查看更多
beautiful°
7楼-- · 2020-07-17 15:19

You should check the working directory of your application. Perhaps it is not the one you assume and that's why 'src' directory is not present.

An easy check for this is to try the absolute path (only for debugging!).

查看更多
登录 后发表回答