How to specify filepath in java?

2019-04-17 12:26发布

I have created a java application for "Debian Linux." Now I want that that application reads a file placed in the directory where the jar file of that application is specified. So what to specify at the argument of the File Object?

File fileToBeReaded = new File(...);

What to specify as argument for the above statement to specify relative filepath representing the path where the jar file of the application has been placed?

5条回答
乱世女痞
2楼-- · 2019-04-17 12:36

If you know the name of the file, of course it's simply

new File("./myFileName")

If you don't know the name, you can use the File object's list() method to get a list of files in the current directory, and then pick the one you want.

查看更多
别忘想泡老子
3楼-- · 2019-04-17 12:44

I think this should do the trick:

File starting = new File(System.getProperty("user.dir"));
File fileToBeRead = new File(starting,"my_file.txt");

This way, the file will be searched in the user.dir property, which will be your app's working directory.

查看更多
走好不送
4楼-- · 2019-04-17 12:47

Are you asking about escape character issues?

If that is the case then use forward slashes instead of backward slashes like

"C:/Users/You/Desktop/test.txt"

instead of

"C:\Users\You\Desktop\test.txt"

查看更多
我想做一个坏孩纸
5楼-- · 2019-04-17 12:51

Using relative paths in java.io.File is fully dependent on the current working directory. This differs with the way you execute the JAR. If you're for example in /foo and you execute the JAR by java -jar /bar/jar/Bar.jar then the working directory is still /foo. But if you cd to /bar/jar and execute java -jar Bar.jar then the working directory is /bar/jar.

If you want the root path where the JAR is located, one of the ways would be:

File root = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI());

This returns the root path of the JAR file (i.o.w. the classpath root). If you place your resource relative to the classpath root, you can access it as follows:

File resource = new File(root, "filename.ext");

Alternatively you can also just use:

File resource = new File(Thread.currentThread().getContextClassLoader().getResource("filename.ext").toURI());
查看更多
时光不老,我们不散
6楼-- · 2019-04-17 13:03

You could ask your classloader to give you the location of the jar:

getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

...but I'd suggest to put the file you are looking for inside your jar file and read it as a resource (getClass().getResourceAsStream( "myFile.txt" )).

查看更多
登录 后发表回答