1. 程式人生 > >FilesUtils將本地檔案讀取並轉為字串

FilesUtils將本地檔案讀取並轉為字串

1.依賴類

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

2.使用

//讀取檔案返回字串
    public static String readFileAsString(String filePath) throws IOException {
        //獲取file
        File file=new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } 
        //限制大小
        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }
        //規定StringBuilder大小
        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 建立位元組輸入流  
        FileInputStream fis = new FileInputStream(filePath);  
        // 建立一個長度為10240的Buffer
        byte[] bbuf = new byte[10240];  
        // 用於儲存實際讀取的位元組數  
        int hasRead = 0;  
        while ( (hasRead = fis.read(bbuf)) > 0 ) {  
            sb.append(new String(bbuf, 0, hasRead));  
        }  
        fis.close();  
        return sb.toString();
     }