chenjiahe
2022-06-15 11f9478b32b710e022c328972fd2e07c72a62df8
提交 | 用户 | age
5c5945 1 package com.hx.util;
E 2
6baa2f 3 import org.apache.commons.io.FileUtils;
C 4
5c5945 5 import java.io.*;
6baa2f 6 import java.net.URL;
5c5945 7
E 8 /**
9  * 文件读取工具类
10  * @author ChenJiaHe
11  * @Date 2020-06-17
12  */
13 public class FileUtil {
14
15     /**
6baa2f 16      * @param pathUrl 网络路径
C 17      * @return 文件
18      */
19     public static File getUrlFile(String pathUrl){
20         File temp = null;
21         try{
22             URL url = new URL(pathUrl);
23             temp = File.createTempFile("temp", ".xls");
24             FileUtils.copyURLToFile(url, temp);
25             temp.deleteOnExit();
26         }catch (Exception e){
27             throw new RuntimeException("通过URL获取文件出错",e);
28         }
29         return temp;
30     }
31
32     /**
5c5945 33      * 读取文件内容,作为字符串返回
E 34      */
35     public static String readFileAsString(String filePath) throws IOException {
36         File file = new File(filePath);
37         if (!file.exists()) {
38             throw new FileNotFoundException(filePath);
39         } 
40
41         if (file.length() > 1024 * 1024 * 1024) {
42             throw new IOException("File is too large");
43         } 
44
45         StringBuilder sb = new StringBuilder((int) (file.length()));
46         // 创建字节输入流  
47         FileInputStream fis = new FileInputStream(filePath);  
48         // 创建一个长度为10240的Buffer
49         byte[] bbuf = new byte[10240];  
50         // 用于保存实际读取的字节数  
51         int hasRead = 0;  
52         while ( (hasRead = fis.read(bbuf)) > 0 ) {  
53             sb.append(new String(bbuf, 0, hasRead));  
54         }  
55         fis.close();  
56         return sb.toString();
57     }
58
59     /**
60      * 根据文件路径读取byte[] 数组
61      */
62     public static byte[] readFileByBytes(String filePath) throws IOException {
63         File file = new File(filePath);
64         if (!file.exists()) {
65             throw new FileNotFoundException(filePath);
66         } else {
67             ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
68             BufferedInputStream in = null;
69
70             try {
71                 in = new BufferedInputStream(new FileInputStream(file));
72                 short bufSize = 1024;
73                 byte[] buffer = new byte[bufSize];
74                 int len1;
75                 while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
76                     bos.write(buffer, 0, len1);
77                 }
78
79                 byte[] var7 = bos.toByteArray();
80                 return var7;
81             } finally {
82                 try {
83                     if (in != null) {
84                         in.close();
85                     }
86                 } catch (IOException var14) {
87                     var14.printStackTrace();
88                 }
89
90                 bos.close();
91             }
92         }
93     }
94 }