chenjiahe
2022-03-04 6baa2fe5af69ab1ff94168231b1dc9af2084ced1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.hx.util;
 
import org.apache.commons.io.FileUtils;
 
import java.io.*;
import java.net.URL;
 
/**
 * 文件读取工具类
 * @author ChenJiaHe
 * @Date 2020-06-17
 */
public class FileUtil {
 
    /**
     * @param pathUrl 网络路径
     * @return 文件
     */
    public static File getUrlFile(String pathUrl){
        File temp = null;
        try{
            URL url = new URL(pathUrl);
            temp = File.createTempFile("temp", ".xls");
            FileUtils.copyURLToFile(url, temp);
            temp.deleteOnExit();
        }catch (Exception e){
            throw new RuntimeException("通过URL获取文件出错",e);
        }
        return temp;
    }
 
    /**
     * 读取文件内容,作为字符串返回
     */
    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();
            }
        }
    }
}