java8之读取txt文件转List<String>

到了java8读取文件内容最好的方式就是用Stream了

桌面有个文件hello.txt,为了方便展示demo,内容是这样的

格式是一行一个英文单词。

看代码

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : 
 * @date : 2018/8/26
 * @description:
 */
public class ReadFile {

    public static  List<String> getContent()  {
        String fileName = "C:\\Users\\Lenovo\\Desktop\\hello.txt";
        //读取文件
        List<String> lineLists = null;
        try {
            System.out.println(fileName);
            lineLists = Files
                    .lines(Paths.get(fileName), Charset.defaultCharset())
                    .flatMap(line -> Arrays.stream(line.split("\n")))
                    .collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  lineLists;
    }

    public static void main(String[] args) {
        List<String> list = ReadFile.getContent();
        for (String s : list) {
            System.out.println(s);
        }
    }
}

看输出

first
second
Third
Fourth
Fifth

注意:

       1.这里文件涉及到了nio的包

        2.路径是绝对路径,路径中使用一个反斜杠 \是转义,所以使用两个,如果使用IDEA它会自动补全成两个

        3.这种方式在idea跑代码正常,但是打成jar在命令行,读取jar外部文件内容的时候会因为nio报错,原因没具体深入查找。

                错误提示:java.nio.charset.MalformedInputException: Input length = 1   

                解决办法:https://blog.csdn.net/Mint6/article/details/82227596  换成Io的方式。

不过java8,项目正常的话用这种方式还是挺舒服的,比较推荐。

猜你喜欢

转载自blog.csdn.net/Mint6/article/details/82227871