package wjb.baidu.ai.utils;

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

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

	/**
	 * 读取文件内容,作为字符串返回
	 */
	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();
			}
		}
	}
}
最近下载更多
coolcool123  LV1 3月17日
lironggang  LV38 2023年4月27日
97622282  LV1 2022年6月7日
王伟杰  LV2 2021年11月12日
淮竹  LV1 2021年10月13日
我是桃子呀  LV3 2021年7月14日
jokerYao  LV1 2020年11月27日
cas  LV9 2020年9月21日
sakura_fc  LV1 2020年9月10日
wanhaiq  LV3 2020年7月2日
最近浏览更多
coolcool123  LV1 3月17日
liyonggang  LV2 1月19日
miaoshi  LV16 1月3日
837055744 2023年7月20日
暂无贡献等级
2017143155  LV12 2023年6月27日
lironggang  LV38 2023年4月27日
nsq0006  LV6 2023年3月3日
lc4519  LV3 2023年3月3日
uni-code_0123  LV1 2023年1月10日
arkic1 2022年12月1日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友