我想要一个java文件的相对路径
我是java新手。我想用java读取一个属性文件。但我的属性文件位于同一项目中的不同路径中 我不想硬编码。我想试试动态路径。 这是我的密码我想要一个java文件的相对路径,java,Java,我是java新手。我想用java读取一个属性文件。但我的属性文件位于同一项目中的不同路径中 我不想硬编码。我想试试动态路径。 这是我的密码 Properties properties = new Properties(); try{ File file = new File("myFile.properties"); FileInputStream fileInput = new FileInputStream(file);
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
中
有人能帮我解决这个问题吗?如果它位于
webapp/txt.myFile.properties
下,并且webapp是公共web空间,那么您需要使用绝对URL来阅读它
getServletContext().getRealpath("/txt/myFile.properties")
Properties prop=新属性();
InputStream输入=getServletContext().getResourceAsStream(“/txt/myFile.properties”);
道具载荷(输入);
System.out.println(prop.getProperty());
解决此问题的一种方法是将文件的绝对路径分为两部分
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
就我所记得的,当这样编码时,它通常会在带有WAR或JAR的文件夹中查找属性文件。
dbProperties = loadDBProperties();
String dbName = dbProperties.getProperty("db.schema");//you can read your line form here of properties file