FileUtil.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package me.zhengjie.base.util.baidu;
  2. import java.io.*;
  3. /**
  4. * 文件读取工具类
  5. */
  6. public class FileUtil {
  7. /**
  8. * 读取文件内容,作为字符串返回
  9. */
  10. public static String readFileAsString(String filePath) throws IOException {
  11. File file = new File(filePath);
  12. if (!file.exists()) {
  13. throw new FileNotFoundException(filePath);
  14. }
  15. if (file.length() > 1024 * 1024 * 1024) {
  16. throw new IOException("File is too large");
  17. }
  18. StringBuilder sb = new StringBuilder((int) (file.length()));
  19. // 创建字节输入流
  20. FileInputStream fis = new FileInputStream(filePath);
  21. // 创建一个长度为10240的Buffer
  22. byte[] bbuf = new byte[10240];
  23. // 用于保存实际读取的字节数
  24. int hasRead = 0;
  25. while ( (hasRead = fis.read(bbuf)) > 0 ) {
  26. sb.append(new String(bbuf, 0, hasRead));
  27. }
  28. fis.close();
  29. return sb.toString();
  30. }
  31. /**
  32. * 根据文件路径读取byte[] 数组
  33. */
  34. public static byte[] readFileByBytes(String filePath) throws IOException {
  35. File file = new File(filePath);
  36. if (!file.exists()) {
  37. throw new FileNotFoundException(filePath);
  38. } else {
  39. ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
  40. BufferedInputStream in = null;
  41. try {
  42. in = new BufferedInputStream(new FileInputStream(file));
  43. short bufSize = 1024;
  44. byte[] buffer = new byte[bufSize];
  45. int len1;
  46. while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
  47. bos.write(buffer, 0, len1);
  48. }
  49. byte[] var7 = bos.toByteArray();
  50. return var7;
  51. } finally {
  52. try {
  53. if (in != null) {
  54. in.close();
  55. }
  56. } catch (IOException var14) {
  57. var14.printStackTrace();
  58. }
  59. bos.close();
  60. }
  61. }
  62. }
  63. }