Newer
Older
osmCoverage / src / tools / Compless.java
@yuu yuu on 24 Dec 2018 3 KB function: UnMapped.
  1. package tools;
  2.  
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.OutputStream;
  10. import java.util.zip.GZIPInputStream;
  11. import org.apache.commons.compress.archivers.ArchiveException;
  12. import org.apache.commons.compress.archivers.ArchiveOutputStream;
  13. import org.apache.commons.compress.archivers.ArchiveStreamFactory;
  14. import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
  15. import org.apache.commons.compress.utils.IOUtils;
  16. import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
  17. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  18.  
  19. public class Compless {
  20. /**
  21. * `.tar.gz`形式のファイルを指定のディレクトリにuncompless
  22. *
  23. * @param outDir
  24. * @param gzipFile
  25. * @throws FileNotFoundException
  26. * @throws IOException
  27. */
  28. public static void uncomplessTarGz(File outDir, File gzipFile) throws FileNotFoundException, IOException {
  29. try (FileInputStream fis = new FileInputStream(gzipFile)) {
  30. try (GZIPInputStream gis = new GZIPInputStream(fis)) {
  31. try (TarArchiveInputStream tis = new TarArchiveInputStream(gis)) {
  32. for (TarArchiveEntry entry = tis.getNextTarEntry(); entry != null; entry = tis.getNextTarEntry()) {
  33. if (entry.isDirectory()) {
  34. File newDir = new File(outDir, entry.getName());
  35. try {
  36. newDir.mkdirs();
  37. }
  38. catch(Exception e) {
  39. throw new IOException("directory '" + newDir.getAbsolutePath() + "' cannot create.");
  40. }
  41. }
  42. else {
  43. File newfile = new File(outDir, entry.getName());
  44. File parentDir = newfile.getParentFile();
  45. try {
  46. parentDir.mkdirs();
  47. }
  48. catch(Exception e) {
  49. throw new IOException("directory '" + parentDir.getAbsolutePath() + "' cannot create.");
  50. }
  51. try (FileOutputStream fos = new FileOutputStream(newfile)) {
  52. IOUtils.copy(tis, fos); // Apache common-io
  53. }
  54. }
  55. }
  56. }
  57. }
  58. }
  59. }
  60. /**
  61. *
  62. * @param sourceFile
  63. * @param zipFile
  64. * @throws FileNotFoundException
  65. * @throws org.apache.commons.compress.archivers.ArchiveException
  66. */
  67. public static void toZip(File sourceFile, File zipFile) throws FileNotFoundException, IOException, ArchiveException {
  68. final OutputStream out = new BufferedOutputStream(new FileOutputStream(zipFile));
  69. try (ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, out)) {
  70. os.putArchiveEntry(new ZipArchiveEntry(sourceFile.getName()));
  71. IOUtils.copy(new FileInputStream(sourceFile), os);
  72. os.closeArchiveEntry();
  73. }
  74. }
  75. }