我有一个Java问题一直困扰着我:如何表示相对文件路径。
让我更具体地说明。我希望能够始终在./configuration/file.txt
中查找配置文件。我的问题是,如果从文件所在的目录以外的不同目录(例如./directory/to/my/program/execute.sh
)启动程序,则它将无法正常工作。
但我还需要更改此文件,而资源似乎只读...
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.collection";
然后,您可以使用类似以下方式检索文件:
String fileLocation = systemDir + "/file.txt";
如果您想让/configuration/file.txt
表示相对于某个文件,您需要定义这个文件是什么。通常我们会将其定义为“类路径或当前目录”。但是,您需要编写一些代码来使其正常工作。以下是大致的代码示例(未经测试)。
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 );
}
./configuration/file.txt
而不是/configuration/file.txt
。第二个路径是绝对路径,不应该有问题。 - Adam Paynter