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