简体   繁体   中英

How can I find a file while in my java code

I am stuck on a how to robustly find a file path from my Java program. If I am using Linux, I can launch my program from my home folder, and then I can't say find my file at ./myProgram/myFile. Is there a good way to find my file no matter what directory my console is in?

If you are trying to access the file using the path:

./myProgram/myFile

in your program, but you aren't executing the program from the myProgram directory, then you're Java code won't see the file. Try providing it with the full path instead of the relative path. If myProgram is a directory found in your user's Documents directory then a full path would likely look something like this:

/home/*username*/Documents/myProgram/myFile

You could also build in functionality that lets you select the file by navigating through the directories and listing the files. The would provide the user with options to choose which file to utilize in the program.

You can just as well cd to the myProgram directory before executing the file and then the relative path ./myProgram/myFile should work.

Hope that helps.

尝试这个:

File f = new File(System.getProperty("user.home") + System.getProperty("file.separator") + "myFile.txt");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM