Java 文件读取工具类

package com.lb.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件读取工具类
 * @author admin
 *
 */
public class ReadUtil {

    /**
     * 要读取的文件的编码, 如果文件编码为 GBK 则要指定 GBK 否则会乱码
     */
    private static final String FILE_CHARSET = "UTF-8";

    public static final List read(String filePath){
        List contents = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), FILE_CHARSET))) {
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                contents.add(line);
            }

            return contents;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static final String readAsString(String filePath){
        StringBuffer sbBuffer = new StringBuffer();

        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), FILE_CHARSET))) {
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                sbBuffer.append(line + "\r\n");
            }

            return sbBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

你可能感兴趣的:(工具类)