web项目和java项目在读取文件时路径是不一样的,在web项目中使用FileReader reader = new FileReader(“("./conf/test.properties”);会报文件找不到异常,下面通过getResourceAsStream获取文件相对路径的方法获取输入流,可以适用在两种项目中。
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.InputStream;
import java.util.Properties;
public class PropLoad {
public static Properties props = new Properties();
static {
InputStream in = null;
try {
in = PropLoad.class.getResourceAsStream("./conf/test.properties");//getClassPath+"conf/test.properties"用这种方式好一些
// reader = new FileReader("conf/conf/test.properties");
props.load(in);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static Properties props = new Properties();
static {
InputStream in = null;
try {
in = PropLoad.class.getResourceAsStream("./conf/test.properties");//getClassPath+"conf/test.properties"用这种方式好一些
// reader = new FileReader("conf/conf/test.properties");
props.load(in);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
可以通过如下方法获取类路径,然后去拼成配置文件的路径,是可以匹配web和java项目的路径的
/**
* 获取类路径
*/
public String getClassPath(){
URL url = This.getClass().getResource("/");
String path = url.getPath();
if(path.startsWith("/")) {
path = path.substring(1);
}
return path;
}
/**
* 获取类路径
*/
public String getClassPath(){
URL url = This.getClass().getResource("/");
String path = url.getPath();
if(path.startsWith("/")) {
path = path.substring(1);
}
return path;
}