文件读取工具类

java

浏览数:867

2019-1-13


FileUtils.java

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

public class FileUtils {
    public final static FileUtils ME = new FileUtils();
    private FileUtils(){}

    public String readFile(String path, String fileName) throws IOException {
        return readFile(path, fileName, System.getProperty("file.encoding"));
    }

    public String readFile(String path, String fileName, String encode) throws IOException {
        if (!path.endsWith("/")){
            path += "/";
        }
        if (fileName.startsWith("/")){
            fileName = fileName.substring(1);
        }
        File file = new File(path+fileName);
        return readFile(file, encode);
    }

    public String readFile(File file, String encode) throws IOException {
        return new String(readFileBin(file), encode);
    }

    public byte[] readFileBin(File file) throws IOException {
        byte[] temp = new byte[1024];
        byte[] result;
        try (FileInputStream in = new FileInputStream(file);ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();) {
            while (true){
                int size = in.read(temp);
                if (size<0){
                    break;
                }
                arrayOut.write(temp, 0, size);
            }
            result = arrayOut.toByteArray();
        }
        return result;
    }
}