如果我有个文件存在src下一级的地方和存在src同级的目录应该怎么用相对路径去获取如图:
一、如果存在src同级的地方应该是InputStream in = new BufferedInputStream(new FileInputStream("./set.properties"));就可以了。
代码如下:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
public class PropertiesUtil {
public static String getUrlValue(String urlName) {
String url = null;
Properties prop = new Properties();
try {
//ConfigUtil.class.getClassLoader().getSystemClassLoader().getResource(""));
ClassLoader classLoader = PropertiesUtil.class.getClassLoader();// 读取属性文件xxxxx.properties
//InputStream in = classLoader.getResourceAsStream("config/config.properties");
InputStream in = new BufferedInputStream(new FileInputStream("./set.properties"));
prop.load(in); /// 加载属性列表
Iterator<String> it = prop.stringPropertyNames().iterator();
while (it.hasNext()) {
if (it.next().equals(urlName)) {
url = prop.getProperty(urlName);
}
}
in.close();
} catch (Exception e) {
}
return url;
}
}
配置文件如:
测试:
import cn.deos.util.PropertiesUtil;
public class test {
public static void main(String []args){
String urlValue = PropertiesUtil.getUrlValue("defaultFileDirectory");
System.out.println("urlValue=="+urlValue);
}
}
二 、如果存在src下一级的地方应该是ClassLoader classLoader = PropertiesUtil.class.getClassLoader();// 读取属性文件xxxxx.properties
//InputStream in = classLoader.getResourceAsStream("set.properties");就可以了。
代码如下:
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
public class PropertiesUtil {
public static String getUrlValue(String urlName) {
String url = null;
Properties prop = new Properties();
try {
ClassLoader classLoader = PropertiesUtil.class.getClassLoader();// 读取属性文件xxxxx.properties
InputStream in = classLoader.getResourceAsStream("config/config.properties");
//InputStream in = new BufferedInputStream(new FileInputStream("set.properties"));
prop.load(in); /// 加载属性列表
Iterator<String> it = prop.stringPropertyNames().iterator();
while (it.hasNext()) {
if (it.next().equals(urlName)) {
url = prop.getProperty(urlName);
}
}
in.close();
} catch (Exception e) {
}
return url;
}
}
测试如下:
import cn.deos.util.PropertiesUtil;
public class test {
public static void main(String []args){
String urlValue = PropertiesUtil.getUrlValue("defaultFileDirectory");
System.out.println("urlValue=="+urlValue);
}
}