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

相關文章
相關標籤/搜索