1.读取绝对路径的方法,也就是我们的本地调试读取
public static void main(String[] args) {
String filePath = “E:\1.txt”;
List text = new ArrayList();
//我的需求是转成list集合,所以我用list接收
text = readTxtFile(filePath,“utf-8”);
System.out.println(text);
}
public List readTxtFile(String filePath,String encoding) {
ArrayList res = new ArrayList();
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 编码格式必须和文件的一致
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
//注意文件里面的格式,我的里面是一行一行的,所以不需要再次切割了,直接添加就行
res.add(lineTxt);
}
read.close();
} else {
System.out.println(“指定的文件不存在”);
}
} catch (Exception e) {
log.error(“readTxtFile”,e);
}
return res;
}
2.读取相对路径的方法,也就是我们在服务器上读取
- 首先把读取的文件放在resources目录下
public Resp styleCodeUpdate() {
String filePath = “exceltemplate/1.txt”;
List text = new ArrayList();
text = styleCodeLayoutService.readTxtFile(filePath,“utf-8”);
List finalText = text;
return Resp.success();
}
public List readTxtFile(String filePath, String encoding) {
List res = new ArrayList();
InputStream is=null;
InputStreamReader isr=null;
try {
is= this.getClass().getClassLoader().getResourceAsStream(filePath);
isr=new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(isr);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
res.add(lineTxt);
}
} catch (Exception e) {
log.error(“readTxtFile”,e);
}finally {
if(is!=null){
try {
is.close();
isr.close();
} catch (IOException e) {}
}
}
return res;
}