在解压前获取文件解压大小,主要为了不解压获取解压后的文件大小,计算解压后的磁盘占用量

 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
<dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding</artifactId>
            <version>16.02-2.01</version>
        </dependency>
        <dependency>
            <groupId>net.sf.sevenzipjbinding</groupId>
            <artifactId>sevenzipjbinding-all-platforms</artifactId>
            <version>16.02-2.01</version>
        </dependency>
        <dependency>
            <groupId>org.tukaani</groupId>
            <artifactId>xz</artifactId>
            <version>1.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.21</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.3</version>
        </dependency>
  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
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import net.sf.sevenzipjbinding.*;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.impl.VolumedArchiveInStream;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

public class Test {
    static List<String> failedList = new ArrayList<>();

    public static void main(String[] args) throws IOException, SevenZipNativeInitializationException {
        // test , sevenzipjbinding 快12.5倍
//        sevenzipjbinding();
//        commonsCompress();
        //统计文件夹中7z和7z.001文件的压缩前大小
        File basePath = new File("\\\\tsclient\\I");
        System.out.println(basePath.listFiles());
        long totalSize = foreachDir(basePath);

        System.out.println(totalSize + " , " + fileSizeConver(totalSize));
        System.out.println(failedList);
    }

    public static long foreachDir(File basePath) {
        AtomicLong totalSize = new AtomicLong();
        File[] files = basePath.listFiles();
        Arrays.stream(files).forEach(file -> {

            if (file.isDirectory()) {
                if (file.getName().startsWith("System ") || file.getName().startsWith("$")) {
                    return;
                }
                System.out.println(file.getAbsolutePath());
                totalSize.addAndGet(foreachDir(file));
            } else {
                if (file.getName().endsWith("7z") || file.getName().endsWith(".7z.001")) {
                    try {
                        System.out.println(file.getAbsolutePath());
                        totalSize.addAndGet(getUnCompressSize(file));
                    } catch (Exception e) {
                        e.printStackTrace();
                        failedList.add(file.getAbsolutePath());
                    }
                }
            }
        });
        return totalSize.get();
    }

    public static long getUnCompressSize(File file) throws Exception {
        IInArchive archive;
        ArchiveOpenVolumeCallback archiveOpenVolumeCallback = null;

        RandomAccessFile randomAccessFile = null;
        if (file.getName().endsWith("7z")) {
            randomAccessFile = new RandomAccessFile(file, "r");

            archive = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP, // null - autodetect
                    new RandomAccessFileInStream(randomAccessFile));
        } else {
            archiveOpenVolumeCallback = new ArchiveOpenVolumeCallback();
            archive = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP,
                    new VolumedArchiveInStream(file.getAbsolutePath(),
                            archiveOpenVolumeCallback));
        }

        int numberOfItems = archive.getNumberOfItems();

        long totalSize = 0;
        for (int i = 0; i < numberOfItems; i++) {
            String name = archive.getStringProperty(i, PropID.PATH);
            Long size = (Long) archive.getProperty(i, PropID.SIZE);
            System.out.println(name + " => " + size + " , " + fileSizeConver(size));
            totalSize += size;
        }
//        System.out.println(totalSize);
        System.out.println(file.getName() + " total => " + fileSizeConver(totalSize));
        archive.close();
        if (randomAccessFile != null)
            randomAccessFile.close();
        if (archiveOpenVolumeCallback != null)
            archiveOpenVolumeCallback.close();
        return totalSize;
    }


    public static void sevenzipjbinding() throws IOException, SevenZipNativeInitializationException {
        //SevenZip.initSevenZipFromPlatformJAR();
        TimeInterval timer = DateUtil.timer();
        File f = new File("\\\\tsclient\\I\\OB\\2021/20210104.7z");
        IInArchive archive;
        RandomAccessFile randomAccessFile;

        randomAccessFile = new RandomAccessFile(f, "r");

        archive = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP, // null - autodetect
                new RandomAccessFileInStream(randomAccessFile));

        int numberOfItems = archive.getNumberOfItems();
// 方式一
//        ISimpleInArchive simpleInterface = archive.getSimpleInterface();
//        simpleInterface.getArchiveItem(0).getSize();

//方拾贰
        long totalSize = 0;
        for (int i = 0; i < numberOfItems; i++) {
            String name = archive.getStringProperty(i, PropID.PATH);
            Long size = (Long) archive.getProperty(i, PropID.SIZE);
            System.out.println(name + " => " + size);
            totalSize += size;
        }
        System.out.println(totalSize);
        System.out.println(fileSizeConver(totalSize));
        archive.close();
        randomAccessFile.close();
        System.out.println(numberOfItems);
        System.out.println(timer.interval());
    }

    public static void commonsCompress() throws IOException {
        TimeInterval timer = DateUtil.timer();
        long totalSize = 0;
        File f = new File("\\\\tsclient\\I\\OB\\2021/20210104.7z");
        SevenZFile sevenZFile = new SevenZFile(f);
        final Iterable<SevenZArchiveEntry> entries = sevenZFile.getEntries();
        for (SevenZArchiveEntry entry : entries) {
            System.out.println(entry.getName());
//            System.out.println(entry.getCompressedSize()); // 文件压缩后大小
            System.out.println(entry.getSize()); // 文件大小
            totalSize += entry.getSize();
        }
        System.out.println(totalSize);
        System.out.println(fileSizeConver(totalSize));
        sevenZFile.close();
        System.out.println(timer.interval());
    }


    private static String fileSizeConver(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    private static class ArchiveOpenVolumeCallback
            implements IArchiveOpenVolumeCallback {

        /**
         * Cache for opened file streams
         */
        private Map<String, RandomAccessFile> openedRandomAccessFileList =
                new HashMap<String, RandomAccessFile>();

        /**
         * This method doesn't needed, if using with VolumedArchiveInStream
         * and pass the name of the first archive in constructor.
         * (Use two argument constructor)
         *
         * @see IArchiveOpenVolumeCallback#getProperty(PropID)
         */
        public Object getProperty(PropID propID) throws SevenZipException {
            return null;
        }

        /**
         * The name of the required volume will be calculated out of the
         * name of the first volume and volume index. If you need
         * need volume index (integer) you will have to parse filename
         * and extract index.
         *
         * <pre>
         * int index = filename.substring(filename.length() - 3,
         *         filename.length());
         * </pre>
         */
        public IInStream getStream(String filename) throws SevenZipException {
            try {
                // We use caching of opened streams, so check cache first
                RandomAccessFile randomAccessFile = openedRandomAccessFileList
                        .get(filename);
                if (randomAccessFile != null) { // Cache hit.
                    // Move the file pointer back to the beginning
                    // in order to emulating new stream
                    randomAccessFile.seek(0);
                    return new RandomAccessFileInStream(randomAccessFile);
                }

                // Nothing useful in cache. Open required volume.
                randomAccessFile = new RandomAccessFile(filename, "r");

                // Put new stream in the cache
                openedRandomAccessFileList.put(filename, randomAccessFile);

                return new RandomAccessFileInStream(randomAccessFile);
            } catch (FileNotFoundException fileNotFoundException) {
                // Required volume doesn't exist. This happens if the volume:
                // 1. never exists. 7-Zip doesn't know how many volumes should
                //    exist, so it have to try each volume.
                // 2. should be there, but doesn't. This is an error case.

                // Since normal and error cases are possible,
                // we can't throw an error message
                return null; // We return always null in this case
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        /**
         * Close all opened streams
         */
        void close() throws IOException {
            for (RandomAccessFile file : openedRandomAccessFileList.values()) {
                file.close();
            }
        }
    }
}