案例一:使用类相对路径,需要读的文件需要放在idea项目名下的resource文件中。这样编译后idea能在存放class文件的项目名对应包下,直接找到文件,读取文件。(通用,代码好移植)
/*pathname传文件名,如/projectDetails.txt*/
public ArrayList<String> readFromTextFile(String pathname) throws IOException {
ArrayList<String> strArray = new ArrayList<String>();
InputStreamReader reader = new InputStreamReader(PriorTest.class.getResourceAsStream(pathname));
BufferedReader br = new BufferedReader(reader);
String line = "";
line = br.readLine();
while (line != null) {
strArray.add(line);
line = br.readLine();
}
reader.close();/*关闭输入流*/
return strArray;
}
案例二:使用绝对路径:
/*pathname传文件名,如/projectDetails.txt或者\\projectDetails.txt*/
public ArrayList<String> readFromTextFile(String pathname) throws IOException {
ArrayList<String> strArray = new ArrayList<String>();
File file = new File("C:\\Users\\HUAWEI\\Desktop\\os"+pathname);
InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
BufferedReader br = new BufferedReader(reader);
String line = "";
line = br.readLine();
while (line != null) {
strArray.add(line);
line = br.readLine();
}
reader.close();/*关闭输入流*/
return strArray;
}
|