package com.zooseefun.util;

import java.io.*;

/**
 * 文件读取工具类
 */
public class FileUtils {

    /**
     * 读取文件内容,作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        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 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();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }
}
最近下载更多
NoirMeow  LV1 2024年5月21日
扫把多啦攻core  LV1 2022年6月5日
ruishent  LV6 2022年3月8日
helenli522  LV1 2021年5月3日
13261713015  LV4 2021年1月4日
guodaxia  LV14 2020年8月31日
磊哥哥哥哥  LV13 2020年5月28日
linghongjun5002  LV10 2020年4月24日
wei112233  LV15 2020年4月21日
zq980707  LV6 2020年4月3日
最近浏览更多
啦啦啦7719  LV15 2024年10月15日
yuanmaxiazai  LV2 2024年6月19日
EIFFELZY 2024年6月4日
暂无贡献等级
a1677596408  LV23 2024年4月26日
诺一啊啊啊啊啊  LV3 2024年4月7日
3334004690  LV11 2024年3月20日
1134116035 2024年2月25日
暂无贡献等级
tr1314qq  LV17 2024年2月5日
暂无贡献等级
2017143155  LV12 2023年6月27日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友