java读取txt文件为List<String>

文件在桌面放着名字为hello.txt,先看一下要读取的内容

这是为了方便展示demo随便写的,格式是一行一个英文单词,一共五个。

读取代码,这个代码也是网上找的,忘了哪个博客了。

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author :
 * @date : 2018/8/30
 * @description:
 */
public class ReaderFileLine {

    /**
    * @author:
    * @date:2018/8/30
    * @description:从txt文件读取List<String>
    */
    public static List<String> getFileContent(String path) {
        List<String> strList = new ArrayList<String>();
        File file = new File(path);
        InputStreamReader read = null;
        BufferedReader reader = null;
        try {
            read = new InputStreamReader(new FileInputStream(file),"utf-8");
            reader = new BufferedReader(read);
            String line;
            while ((line = reader.readLine()) != null) {
                strList.add(line);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
        return strList;
    }

    public static void main(String[] args) {
        List<String> fileContent = 
        ReaderFileLine.getFileContent("C:\\Users\\Lenovo\\Desktop\\hello.txt");
        for (String s : fileContent) {
            System.out.println(s);
        }
    }

}

输出:

first
second
Third
Fourth
Fifth

注意:

     1.这里File这个类导入的包是Io的,不是Nio的

     2. ReaderFileLine.getFileContent("C:\\Users\\Lenovo\\Desktop\\hello.txt");  这个路径是绝对路径

     3.路径是一个 反斜杠 \  但是在代码里面反斜杠是转义的意思,所以需要再加一个\,如果你是用的IDEA恭喜你,它会自动给你加上

如果你用的java8推荐这种方式:https://blog.csdn.net/Mint6/article/details/82227871

  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值