我想要一个java文件的相对路径



我是java新手。我想用java读取一个属性文件。但我的属性文件在同一个项目的不同路径中。

我不想硬编码。我想尝试动态路径。这是我的代码,

Properties properties = new Properties();
try{
File file = new File("myFile.properties");
FileInputStream fileInput = new FileInputStream(file);
properties.load(fileInput);
}catch(Exception ex)
{
System.err.println(ex.getMessage());
}

我的文件在文件夹webapp/txt/myFile.properties中。

有人能帮我解决这个问题吗?。

解决此问题的一种方法是将文件的绝对路径拆分为两部分

  1. 项目文件夹的路径
  2. 从项目文件夹开始的路径(相对路径)

您可以在应用程序中处理这两个属性,并连接并获取文件的绝对路径。相对路径保持可配置状态。

public Properties loadDBProperties() {
InputStream dbPropInputStream = null;
dbPropInputStream = DbConnection.class
.getResourceAsStream("MyFile.properties");
dbProperties = new Properties();
try {
dbProperties.load(dbPropInputStream);
} catch (IOException ex) {
ex.printStackTrace();
}
return dbProperties;
}

你可以从调用这个方法

dbProperties = loadDBProperties();
String dbName = dbProperties.getProperty("db.schema");//you can read your line form here of properties file

如果它在webapp/txt.myFile.properties和webapp下是公共网络空间,那么你需要使用绝对URL 来读取它

getServletContext().getRealpath("/txt/myFile.properties")
Properties prop=new Properties();
InputStream input = getServletContext().getResourceAsStream("/txt/myFile.properties");
prop.load(input);
System.out.println(prop.getProperty(<PROPERTY>));

最新更新