2015-02-22

[Java] 讀取全部的檔案內容到字串

Scanner
import java.io.File;
import java.util.Scanner;

public class TestScanner {

    public static void main(String[] args) throws Throwable {
        Scanner sc = new Scanner(new File("input.txt"), "UTF8");
        String inputStr = sc.useDelimiter("\\Z").next();
        sc.close();

        System.out.println(inputStr);
    }
}
useDelimiter 是設置讀取的正規表示式分隔符,這裡可以用 "\\A" 或 "\\Z"
\A : 輸入的開始。
\Z : 輸入的結尾去掉結尾符號的部分。


Java 7 readAllBytes
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;

public class TestReadAllBytes {

    public static void main(String[] args) throws Exception {
        String inputStr = new String(readAllBytes(get("input.txt")), "UTF8");
        System.out.println(inputStr);
    }
}


Apache Commons IO
import java.io.File;

import org.apache.commons.io.FileUtils;

public class TestReadFileToString {

    public static void main(String[] args) throws Throwable {
        File file = new File("input.txt");
        String inputStr = FileUtils.readFileToString(file, "UTF8");
        System.out.println(inputStr);
    }
}


DataInputStream available
import java.io.DataInputStream;
import java.io.FileInputStream;

public class TestDataInputStream {

    public static void main(String[] args) throws Exception {

        FileInputStream fileStream = new FileInputStream ("input.txt");
        DataInputStream dis = new DataInputStream (fileStream);

        byte[] datainBytes = new byte[dis.available()];
        dis.readFully(datainBytes);
        dis.close();

        String inputStr = new String(datainBytes, "UTF8");
        System.out.println(inputStr);
    }
}

沒有留言:

張貼留言

你好!歡迎你在我的 Blog 上留下你寶貴的意見。