yangys
2025-09-05 5d99227a97b7b244893b748af28e7f78238d2951
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
package org.springblade.mdm.utils;
 
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.tool.utils.FileUtil;
 
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
 
public class ZipTextFileContentUtil {
 
    public static String getTextContent(InputStream inputStream,String entryName) throws IOException {
        String result  = "";
        try(inputStream){
            Path tempZipFile = createTempFile(inputStream);
 
            ZipEntry entry;
            try (java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(tempZipFile.toFile())) {
                Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    entry = entries.nextElement();
                    if (!entryName.equals(entry.getName())) {
                        continue;
                    }
                    try (InputStream fileIns = zipFile.getInputStream(zipFile.getEntry(entryName))) {
                        ByteArrayInputStream bos = new ByteArrayInputStream(fileIns.readAllBytes());
                        boolean isText = StringUtils.endsWithIgnoreCase(entryName,".txt") || StringUtils.endsWithIgnoreCase(entryName,".nc")|| StringUtils.endsWithIgnoreCase(entryName,".xml");
                        if(!isText) {
                            isText = FileContentUtil.isTextFile(bos);
                        }
                        if (isText) {
                            bos.reset();
                            result = FileContentUtil.getContentFromStream(bos);
                        } else {
                            result = "<非文本文件>";
                        }
                    }
 
                }
            }
        }
        return result;
    }
 
    /**
     * 创建一个临时i文件
     * @param inputStream 输入流
     * @return 文件路径
     * @throws IOException
     */
    public static Path createTempFile(InputStream inputStream) throws IOException {
        byte[] zipData = FileUtil.copyToByteArray(inputStream);
        Path tempFile = Files.createTempFile("tempzip"+System.currentTimeMillis(), ".zip");
        // 写入字节数据到临时文件
        Files.write(tempFile, zipData, StandardOpenOption.WRITE);
 
        return tempFile;
    }
}