whyclxw
7 天以前 669906b87674d4b60a6fd5ea3a938c636952dbc2
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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package com.whyc.util;
 
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
 
public class FileUtil {
 
 
    public static List<String> getStaticFilePath(File file, List<String> list){
 
        //如果是文件的情况
        if (file.isFile()){
            list.add(file.getAbsolutePath());
        }else{
            //如果是目录的情况
            //创建一个File数组来存储当前目录下所有文件和目录的绝对路径
            File[] files = file.listFiles();
            //循环遍历files
            for (File fileTemp : files){
                if(fileTemp.getName().contains(".zip")){
                    continue;
                }
                //子级是目录
                if (fileTemp.isDirectory()){
                    //递归再次进行判断
                    getStaticFilePath(fileTemp, list);
                }else{
                    //子级是文件
                    String absolutePath = fileTemp.getAbsolutePath();
                    list.add(absolutePath);
                    //System.out.println(temp + "文件 :" + fileTemp.getName() + "\t");
                }
            }
        }
        return list;
    }
 
    public static List<String> getStaticFilePathII(File file, List<String> list){
 
        //如果是文件的情况
        if (file.isFile()){
            list.add(file.getAbsolutePath());
        }else{
            //如果是目录的情况
            //创建一个File数组来存储当前目录下所有文件和目录的绝对路径
            File[] files = file.listFiles();
            //循环遍历files
            for (File fileTemp : files){
                //子级是目录
                if (fileTemp.isDirectory()){
                    //递归再次进行判断
                    getStaticFilePathII(fileTemp, list);
                }else{
                    //子级是文件
                    String absolutePath = fileTemp.getAbsolutePath();
                    list.add(absolutePath);
                    //System.out.println(temp + "文件 :" + fileTemp.getName() + "\t");
                }
            }
        }
        return list;
    }
 
    public static Boolean deleteFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            System.out.println("文件删除失败,请检查文件是否存在以及文件路径是否正确");
            return false;
        }
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                //递归删除目录下的文件
                deleteFile(f);
            } else {
                //文件删除
                f.delete();
                //打印文件名
            }
        }
        //文件夹删除
        file.delete();
        return true;
    }
 
    public static void download(HttpServletResponse resp,String inFilePath,String outFileFullName){
        try {
            // 转码防止乱码
            //resp.addHeader("Content-Disposition", "attachment;filename=" + new String(softwareName.getBytes("UTF-8"), "ISO8859-1"));
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode ( outFileFullName, "utf-8"));
            OutputStream out = resp.getOutputStream();
            FileInputStream in = new FileInputStream(inFilePath);
            int len=0;
            byte[] buffer =new byte[1024];
            //7. 将缓冲区中的数据输出
            while ((len=in.read(buffer))>0){
                out.write(buffer,0,len);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static String saveFile(MultipartFile multipartFile,String fileName) throws IOException {
        String rootFile = CommonUtil.getRootFile();
 
        String filePath = rootFile + fileName;
        File file = new File(filePath);
        File parentFile = file.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        //存储
        multipartFile.transferTo(file);
        return "pis_file"+fileName;
    }
 
    /**
     * 复制文件夹内的所有文件到另一个文件夹
     */
    public static void copyDirectory(File source, File destination) {
        if (source.isDirectory()) {
            if (!destination.exists()) {
                destination.mkdir();
            }
            for (File file : source.listFiles()) {
                copyDirectory(file, new File(destination, file.getName()));
            }
        } else {
            try (FileInputStream inputStream = new FileInputStream(source);
                 FileOutputStream outputStream = new FileOutputStream(destination)) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 解压N层
     * @param compressedFileUrl doc_file/xxx/xxx.zip 或者 rar
     * @return
     */
    public static List<String> decompress(String compressedFileUrl) throws ArchiveException, IOException, InterruptedException {
        List<Object> resList = decompressOne(compressedFileUrl);
        File outputFolderFile = (File) resList.get(0);
        List<String>  fileList = (List<String>) resList.get(1);
        boolean existCompressedFile = false;
        int checkDecompress = 0;
        //遍历文件列表,判断是否存在压缩文件
        for(String tempFileName:fileList){
            if(tempFileName.endsWith("zip") || tempFileName.endsWith("rar")){
                //存在压缩文件,解压一次
                decompressOne(tempFileName);
                File file = new File(tempFileName);
                //解除文件占用并删除文件
                //boolean delete = file.delete();
                Files.delete(file.toPath());
                existCompressedFile = true;
            }
        }
        //如果存在压缩文件并已解压,则需要检查一次是否还有压缩文件
        if(existCompressedFile){
            checkDecompress ++;
        }
        for (int i = 0; i < checkDecompress; i++) {
            decompress(compressedFileUrl);
        }
 
        List<String> finalList = new LinkedList<>();
        getStaticFilePathII(outputFolderFile,finalList);
        return finalList;
    }
 
    /**
     * 解压一层
     * @param compressedFileUrl doc_file/xxx/xxx.zip 或者 rar
     * @return
     */
    public static List<Object> decompressOne(String compressedFileUrl) throws IOException, ArchiveException, InterruptedException {
        List<Object> resList = new LinkedList<>();
        String projectDir = CommonUtil.getProjectDir() + File.separator;
        String fullFilePath;
        String separator = File.separator;
        String outputFolderSuffix;
        if(compressedFileUrl.startsWith(projectDir)) { // 非第一层解压,已经是全路径
            fullFilePath = compressedFileUrl;
            compressedFileUrl = compressedFileUrl.substring(compressedFileUrl.indexOf("decompress")+11);
            //outputFolderSuffix = compressedFileUrl.substring(0,compressedFileUrl.lastIndexOf(separator)) + separator + "decompress_" + compressedFileUrl.substring(compressedFileUrl.lastIndexOf(separator)+1);
            outputFolderSuffix = compressedFileUrl +"_decompress";
        }else{ //第一层解压
            fullFilePath = projectDir + compressedFileUrl;
            outputFolderSuffix = compressedFileUrl.replace(separator, "@");
        }
        File file = new File(fullFilePath);
 
 
        String outputFolder = CommonUtil.getRootFile() + separator + "decompress" + separator + outputFolderSuffix;
        File outputFolderFile = new File(outputFolder);
        if(!outputFolderFile.exists()){
            outputFolderFile.mkdirs();
            if(compressedFileUrl.endsWith("zip")){
                decompressZip(file, outputFolder);
            }else { //rar
                decompressRar(file, outputFolder);
            }
        }
        //返回文件夹所有文件
        LinkedList<String> list = new LinkedList<>();
        getStaticFilePathII(outputFolderFile,list);
        resList.add(outputFolderFile);
        resList.add(list);
        return resList;
    }
 
    private static void decompressZip(File file, String outputFolder) throws IOException, ArchiveException {
        ArchiveInputStream ais = new ArchiveStreamFactory("GBK").createArchiveInputStream("zip", new FileInputStream(file));
        ArchiveEntry entry;
        while ((entry = ais.getNextEntry()) != null) {
            if (!ais.canReadEntryData(entry) || entry.isDirectory()) {
                continue;
            }
            byte[] buffer = new byte[4096];
            int bytesRead;
            String entryName = entry.getName();
            //if(entryName.contains(File.separator)){
            if(entryName.contains("/")){
                String entryNameDir = entryName.substring(0, entryName.lastIndexOf("/"));
                String entryDirStr = outputFolder + File.separator + entryNameDir;
                File entryDir = new File(entryDirStr);
                if(!entryDir.exists()){
                    entryDir.mkdirs();
                }
            }
 
            OutputStream outputStream = new FileOutputStream(new File(outputFolder + File.separator + entryName));
 
            while ((bytesRead = ais.read(buffer)) > -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
 
            //关流
            outputStream.close();
        }
        //关流
        ais.close();
 
    }
    private static void decompressRar(File file, String outputFolder) throws IOException, InterruptedException {
        String winrarPath = "C:\\Program Files\\WinRAR\\WinRAR.exe";
        String cmd = winrarPath + " X " + file + " " + outputFolder;
        Process proc = Runtime.getRuntime().exec(cmd);
        proc.waitFor();
    }
 
    //读取文件夹下的所有文件(不读取文件夹内的文件)
    public static List getFileNameWithOutDirectory(String filePath) {
        File folder = new File(filePath); // 文件夹路径
        List nameList=new ArrayList();
        File[] listOfFiles = folder.listFiles();
        if (listOfFiles != null) {
            for (File file : listOfFiles) {
                if (file.isFile()) {
                    nameList.add(file.getName());
                }
            }
        }
        return nameList;
    }
 
    //private static void decompressRar(File file, String outputFolder) throws IOException, RarException {
    //    Archive archive = new Archive(file);
    //    FileHeader fileHeader = archive.nextFileHeader();
    //    if (fileHeader != null) {
    //        while (fileHeader != null) {
    //            if (fileHeader.isDirectory()) {
    //                fileHeader = archive.nextFileHeader();
    //                continue;
    //            }
    //            String tempFilePath = fileHeader.getFileName();
    //            File out = new File(outputFolder + File.separator + tempFilePath);
    //            if (!out.exists()) {
    //                if (!out.getParentFile().exists()) {
    //                    out.getParentFile().mkdirs();
    //                }
    //                out.createNewFile();
    //            }
    //            FileOutputStream os = new FileOutputStream(out);
    //            archive.extractFile(fileHeader, os);
    //            os.close();
    //            fileHeader = archive.nextFileHeader();
    //        }
    //    }
    //    archive.close();
    //
    //}
 
    public static void main(String[] args) {
        //File file = new File("C:\\Users\\29550\\Desktop\\AppScan10.rar");
        File file = new File("C:\\code\\web\\CadDrawManager\\target\\doc_file\\decompress\\doc_file@product@FBS-9600-GDPDX-XS1-DC220V-JH@standard@3@3++.rar");
        if(file.exists()) {
            boolean delete = file.delete();
            System.out.println(delete);
        }
    }
}