java读取txt文件的每一行,绝对路径和相对路径的写法

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.读取相对路径的方法,也就是我们在服务器上读取

  1. 首先把读取的文件放在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;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值