FileUtils.java 8.1 KB
Newer Older
RuoYi's avatar
RuoYi committed
1 2
package com.ruoyi.common.utils.file;

jianglw's avatar
jianglw committed
3
import java.io.*;
RuoYi's avatar
RuoYi committed
4
import java.net.URLEncoder;
5
import java.nio.charset.StandardCharsets;
RuoYi's avatar
RuoYi committed
6
import javax.servlet.http.HttpServletRequest;
7
import javax.servlet.http.HttpServletResponse;
jianglw's avatar
jianglw committed
8

9 10
import org.apache.commons.lang3.ArrayUtils;
import com.ruoyi.common.utils.StringUtils;
jianglw's avatar
jianglw committed
11
import org.springframework.web.multipart.MultipartFile;
RuoYi's avatar
RuoYi committed
12 13 14

/**
 * 文件处理工具类
jianglw's avatar
jianglw committed
15
 *
RuoYi's avatar
RuoYi committed
16 17
 * @author ruoyi
 */
jianglw's avatar
jianglw committed
18
public class FileUtils extends org.apache.commons.io.FileUtils {
RuoYi's avatar
RuoYi committed
19 20
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

jianglw's avatar
jianglw committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    /**
     * 读取json文件
     * @param file
     * @return
     * @throws IOException
     */
    public static String readFileJson(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8 );
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        inputStream.close();
        reader.close();
        return sb.toString();
    }
jianglw's avatar
jianglw committed
39 40 41 42 43 44 45 46 47 48 49 50
    public static String readFileJson(File file) throws IOException {
        InputStream inputStream =new FileInputStream( file ) ;
        Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8 );
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        inputStream.close();
        reader.close();
        return sb.toString();
    }
jianglw's avatar
jianglw committed
51

RuoYi's avatar
RuoYi committed
52 53
    /**
     * 输出指定文件的byte数组
jianglw's avatar
jianglw committed
54
     *
RuoYi's avatar
RuoYi committed
55
     * @param filePath 文件路径
jianglw's avatar
jianglw committed
56
     * @param os       输出流
RuoYi's avatar
RuoYi committed
57 58
     * @return
     */
jianglw's avatar
jianglw committed
59
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
RuoYi's avatar
RuoYi committed
60
        FileInputStream fis = null;
jianglw's avatar
jianglw committed
61 62 63 64
        try {
            File file = new File( filePath );
            if (!file.exists()) {
                throw new FileNotFoundException( filePath );
RuoYi's avatar
RuoYi committed
65
            }
jianglw's avatar
jianglw committed
66
            fis = new FileInputStream( file );
RuoYi's avatar
RuoYi committed
67 68
            byte[] b = new byte[1024];
            int length;
jianglw's avatar
jianglw committed
69 70
            while ((length = fis.read( b )) > 0) {
                os.write( b, 0, length );
RuoYi's avatar
RuoYi committed
71
            }
jianglw's avatar
jianglw committed
72
        } catch (IOException e) {
RuoYi's avatar
RuoYi committed
73
            throw e;
jianglw's avatar
jianglw committed
74 75 76
        } finally {
            if (os != null) {
                try {
RuoYi's avatar
RuoYi committed
77
                    os.close();
jianglw's avatar
jianglw committed
78
                } catch (IOException e1) {
RuoYi's avatar
RuoYi committed
79 80 81
                    e1.printStackTrace();
                }
            }
jianglw's avatar
jianglw committed
82 83
            if (fis != null) {
                try {
RuoYi's avatar
RuoYi committed
84
                    fis.close();
jianglw's avatar
jianglw committed
85
                } catch (IOException e1) {
RuoYi's avatar
RuoYi committed
86 87 88 89 90 91
                    e1.printStackTrace();
                }
            }
        }
    }

jianglw's avatar
jianglw committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    /**
     * 删除文件夹下所有文件
     *
     * @param file
     */
    public static void deleteFiles(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println( "文件删除失败,请检查文件路径是否正确" );
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //打印文件名
            String name = f.getName();
            System.out.println();
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                deleteFiles( f );
            } else {
                f.delete();
            }
        }
        //删除空文件夹  for循环已经把上一层节点的目录清空。
        file.delete();
    }

RuoYi's avatar
RuoYi committed
121 122
    /**
     * 删除文件
jianglw's avatar
jianglw committed
123
     *
RuoYi's avatar
RuoYi committed
124 125 126
     * @param filePath 文件
     * @return
     */
jianglw's avatar
jianglw committed
127
    public static boolean deleteFile(String filePath) {
RuoYi's avatar
RuoYi committed
128
        boolean flag = false;
jianglw's avatar
jianglw committed
129
        File file = new File( filePath );
RuoYi's avatar
RuoYi committed
130
        // 路径为文件且不为空则进行删除
jianglw's avatar
jianglw committed
131
        if (file.isFile() && file.exists()) {
RuoYi's avatar
RuoYi committed
132 133 134 135 136 137 138 139
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
jianglw's avatar
jianglw committed
140
     *
RuoYi's avatar
RuoYi committed
141 142 143
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
jianglw's avatar
jianglw committed
144 145
    public static boolean isValidFilename(String filename) {
        return filename.matches( FILENAME_PATTERN );
RuoYi's avatar
RuoYi committed
146 147
    }

148 149
    /**
     * 检查文件是否可下载
jianglw's avatar
jianglw committed
150
     *
151 152 153
     * @param resource 需要下载的文件
     * @return true 正常 false 非法
     */
jianglw's avatar
jianglw committed
154
    public static boolean checkAllowDownload(String resource) {
155
        // 禁止目录上跳级别
jianglw's avatar
jianglw committed
156
        if (StringUtils.contains( resource, ".." )) {
157 158 159 160
            return false;
        }

        // 检查允许下载的文件规则
jianglw's avatar
jianglw committed
161
        if (ArrayUtils.contains( MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType( resource ) )) {
162 163 164 165 166 167 168
            return true;
        }

        // 不在允许下载的文件规则
        return false;
    }

RuoYi's avatar
RuoYi committed
169 170
    /**
     * 下载文件名重新编码
jianglw's avatar
jianglw committed
171 172
     *
     * @param request  请求对象
RuoYi's avatar
RuoYi committed
173 174 175
     * @param fileName 文件名
     * @return 编码后的文件名
     */
jianglw's avatar
jianglw committed
176 177
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader( "USER-AGENT" );
RuoYi's avatar
RuoYi committed
178
        String filename = fileName;
jianglw's avatar
jianglw committed
179
        if (agent.contains( "MSIE" )) {
RuoYi's avatar
RuoYi committed
180
            // IE浏览器
jianglw's avatar
jianglw committed
181 182 183
            filename = URLEncoder.encode( filename, "utf-8" );
            filename = filename.replace( "+", " " );
        } else if (agent.contains( "Firefox" )) {
RuoYi's avatar
RuoYi committed
184
            // 火狐浏览器
jianglw's avatar
jianglw committed
185 186
            filename = new String( fileName.getBytes(), "ISO8859-1" );
        } else if (agent.contains( "Chrome" )) {
RuoYi's avatar
RuoYi committed
187
            // google浏览器
jianglw's avatar
jianglw committed
188 189
            filename = URLEncoder.encode( filename, "utf-8" );
        } else {
RuoYi's avatar
RuoYi committed
190
            // 其它浏览器
jianglw's avatar
jianglw committed
191
            filename = URLEncoder.encode( filename, "utf-8" );
RuoYi's avatar
RuoYi committed
192 193 194
        }
        return filename;
    }
195 196 197 198

    /**
     * 下载文件名重新编码
     *
jianglw's avatar
jianglw committed
199
     * @param response     响应对象
200 201 202
     * @param realFileName 真实文件名
     * @return
     */
jianglw's avatar
jianglw committed
203 204
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode( realFileName );
205 206

        StringBuilder contentDispositionValue = new StringBuilder();
jianglw's avatar
jianglw committed
207 208 209 210 211 212 213 214
        contentDispositionValue.append( "attachment; filename=" )
                .append( percentEncodedFileName )
                .append( ";" )
                .append( "filename*=" )
                .append( "utf-8''" )
                .append( percentEncodedFileName );

        response.setHeader( "Content-disposition", contentDispositionValue.toString() );
215 216 217 218 219 220 221 222
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
jianglw's avatar
jianglw committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode( s, StandardCharsets.UTF_8.toString() );
        return encode.replaceAll( "\\+", "%20" );
    }

//    生成文件
    public static void createdFile(String fileName,String userName,String createdPath,String data) throws IOException {
        FileWriter writer = null;
        try {
            //創建文件夾
            File m=new File(createdPath+userName);
            //判断文件夹存在否
            if(!m.exists()){
                //创建文件夹
                m.mkdir();
            }
            //創建文件
            m=new File(createdPath+userName+"/"+fileName);
            if(!m.exists()){
                //创建文件
                m.createNewFile();
            }
            writer = new FileWriter(createdPath+userName+"/"+fileName);
            writer.write( data );
            writer.flush();
        }finally {
            assert writer != null;
            writer.close();
        }
252
    }
RuoYi's avatar
RuoYi committed
253
}