记录一下在maven项目下访问resources的资源文件
import java.net.URL;
@Test
public void t1() {
URL url = Acc.class.getClassLoader().getResource("study/text.txt");
System.out.println(url.toString());
//url的路径为: file:/C:/Tools/work/studyTest/target/classes/study/text.txt
File file = new File(url.getFile());
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
BufferedReader br = new BufferedReader(reader);
String line = "";
line = br.readLine(); //一次读取一行数据
while(line != null){
System.out.println(line);
line = br.readLine(); //一次读取一行数据
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
注:getResource("study/text.txt") 中study前面不加“/”
getResourceAsStream("study/text.txt"); 中study前面也不加“/”
或者:
@Test
public void t2() {
InputStream stream = Acc.class.getClassLoader().getResourceAsStream("study/text.txt");
InputStreamReader reader = new InputStreamReader(stream);
try {
BufferedReader br = new BufferedReader(reader);
String line = "";
line = br.readLine(); //一次读取一行数据
while(line != null){
System.out.println(line);
line = br.readLine(); //一次读取一行数据
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}