java读取.properties配置文件
为了以后更好管理数据库,将用户上传的文件放入服务器的某个文件夹中管理。在数据库中只存入文件名,而路径前缀写在配置文件中,这样,若改变文件夹位置也无需该数据库,只需改变配置文件。
1、配置文件file.properties
文件在resources下面:
fileUrl = F:\\IdeaProjects\\UserFile\\
2、java代码
获得配置文件的相对路径:
选中文件右键,选择Copy Relative Path,粘贴即可。就是下面的filename。
public String getFileUrl(){
String h=null;
String filename = "file.properties";//配置文件相对路径
Properties properties = new Properties();
try {
properties.load(FileUtil.class.getClassLoader().getResourceAsStream(filename));
h = properties.getProperty("fileUrl");
} catch (IOException e) {
System.out.println("读取配置文件失败");
}
return h;
}
3、测试代码
public class PropertiesTest {
public static void main(String[] args) throws Exception{
String url = new FileUtil().getFileUrl();
System.out.println(url);
}
}
4、结果
F:\IdeaProjects\UserFile\
Process finished with exit code 0