OSDN Git Service

MAVEN構成
[importpicture/importpicture.git] / src / main / java / osm / jp / gpx / utils / TarGz.java
1 package osm.jp.gpx.utils;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9
10 import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
11 import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
12 import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
13
14 /**
15  * 「*.tar.gz」を解凍する。
16  * ファイル更新日時をオリジナルと同じにします。
17  * Apache Commons Compressライブラリ
18  *      commons-compress-1.14.jar
19  */
20 public abstract class TarGz
21 {
22     public static void main(String[] args) throws IOException {
23         File baseDir = new File("testdata/cameradata");
24         File tazFile = new File("testdata", "Sony20170518.tar.gz");
25         TarGz.uncompress(tazFile, baseDir);
26     }
27      
28     /**
29      * *.tar.gz解凍
30      * ファイル更新日時をオリジナルと同じにします。
31      * @param tazFile 解凍する*.tar.gzファイル
32      * @param dest 解凍先フォルダ
33      * @throws IOException 
34      */
35     public static void uncompress(File tazFile, File dest) throws IOException {
36         dest.mkdir();
37         
38         TarArchiveInputStream tarIn = null;
39         tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tazFile))));
40
41         TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
42         while (tarEntry != null) {
43             File destPath = new File(dest, tarEntry.getName());
44             System.out.println("uncompress: " + destPath.getCanonicalPath());
45             if (tarEntry.isDirectory()) {
46                 destPath.mkdirs();
47             }
48             else {
49                 File dir = new File(destPath.getParent());
50                 if (!dir.exists()) {
51                     dir.mkdirs();
52                 }
53                 destPath.createNewFile();
54                 byte[] btoRead = new byte[1024];
55                 try (BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath))) {
56                     int len = 0;
57                     while ((len = tarIn.read(btoRead)) != -1) {
58                         bout.write(btoRead, 0, len);
59                     }
60                 }
61                 destPath.setLastModified(tarEntry.getLastModifiedDate().getTime());
62                 btoRead = null;
63             }
64             tarEntry = tarIn.getNextTarEntry();
65         }
66         tarIn.close();
67     }
68 }