java nio 读取文本文件

这两天在看nio,忽然发现nio中有一个方法一句话就能够读取整个文本文件java

package com.changgx.nio;/**
 * Created by Administrator on 2016/12/14.
 */

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;

import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Files.readAllLines;
import static java.nio.file.Paths.get;

/**
 * Administrator 2016/12/14
 */
public class NioReadFile {
    public static void main(String[] args) throws IOException {
//        Path path = Paths.get("E://学习资料//account.txt");
//        readAllLines() 默认使用的字符编码是utf-8
        List list = (readAllLines(get("E://学习资料//account.txt"), Charset.forName("gbk")));
        String str = new String(readAllBytes(get("E://学习资料//account.txt")),"gbk");
        System.out.println(list);
        System.out.println(str);
    }
}

开始看的时候还觉得是什么高大上的东西,最后查看了源码,发现就是对普通的io进行了一层封装而已app

readAllLines源码学习

public static List<String> readAllLines(Path path, Charset cs) throws IOException {
        try (BufferedReader reader = newBufferedReader(path, cs)) {
            List<String> result = new ArrayList<>();
            for (;;) {
                String line = reader.readLine();
                if (line == null)
                    break;
                result.add(line);
            }
            return result;
        }
    }

newBufferedReader源码google

public static BufferedReader newBufferedReader(Path path, Charset cs)
        throws IOException
    {
        CharsetDecoder decoder = cs.newDecoder();
        Reader reader = new InputStreamReader(newInputStream(path), decoder);
        return new BufferedReader(reader);
    }

中间还遇见了一个异常,google了发现是字符编码的问题,改下读取文件时的字符编码就能够勒编码

Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1 at java.nio.charset.CoderResult.throwException(CoderResult.java:281) at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178) at java.io.InputStreamReader.read(InputStreamReader.java:184) at java.io.BufferedReader.fill(BufferedReader.java:161) at java.io.BufferedReader.readLine(BufferedReader.java:324) at java.io.BufferedReader.readLine(BufferedReader.java:389) at java.nio.file.Files.readAllLines(Files.java:3202) at java.nio.file.Files.readAllLines(Files.java:3239) at com.changgx.nio.NioReadFile.main(NioReadFile.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)code

相关文章
相关标签/搜索