Java relative file paths

2020-02-24 04:13发布

I've got a Java question that I've been having a trouble with: what is a good way to indicate relative file paths.

Let me be more specific. I want to be able to say to always look for configuration files in ./configuration/file.txt. The problem I'm having is that my program will only work correctly if it is started from the directory the file is in. If instead I start it from a different directory like ./directory/to/my/program/execute.sh then it fails to function correctly.

But I also need to make changes to this file, and resources seem to want to be read-only...

标签: java file
4条回答
等我变得足够好
2楼-- · 2020-02-24 04:36

To ensure your data is always in the same location you can make use of the home directory. Making use of the home directory will give you some consistency across different platforms and your program can access the data regardless of the directory it is in.

For example:

String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.collection";

And then you can retrieve a file later with something like

String fileLocation = systemDir + "/file.txt";
查看更多
Explosion°爆炸
3楼-- · 2020-02-24 04:40

If you want /configuration/file.txt to denote a file relative to something, you'll have to define what that something is. We usually let that something be "the classpath or the current directory". You will have to write some code to make that work though. Something along the lines of the following (not tested).

public InputStream getResource( String path ) throws IOException {
  // try relative to current directory
  File file = new File( path );
  if ( file.exists() ) {
    return new FileInputStream( file );
  }
  // try the classpath
  return Thread.currentThread().getContextClassLoader().getResourceAsStream( path );
}
查看更多
We Are One
4楼-- · 2020-02-24 04:49

The suggested (so that the app is independent of the environment specific details) way to read configuration information is to read it as a classpath resource rather than a file system resource. Read Smartly load your properties for more details.

Read Class.getResourceAsStream javadoc for syntax on how to specify the resource path

Useful post on SO: Classpath resource within jar

查看更多
Animai°情兽
5楼-- · 2020-02-24 04:49

You need to provide a mechanism for defining a directory, like through an environment variable, a command-line argument, config file, the preferences API, etc.

查看更多
登录 后发表回答