| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Java Zipファイルの処理

提供: MyMemoWiki
2020年2月16日 (日) 04:27時点におけるPiroto (トーク | 投稿記録)による版
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

Java Zipファイルの処理

Java | Javaコード片 |

参照

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.util.zip.ZipEntry;
  5. import java.util.zip.ZipInputStream;
  6.  
  7. public abstract class LogAnalyzer{
  8.  
  9. // ファイルの配列を処理する
  10. public void analyze(File[] logs) {
  11. try {
  12. for (File log : logs) {
  13. if (log.getName().endsWith("zip")) {
  14. analyzeZipFile(log);
  15. } else {
  16. analyzeTextFile(log);
  17. }
  18. }
  19. } catch (Exception e) {
  20. //TODO
  21. e.printStackTrace();
  22. }
  23. }
  24.  
  25. // Zipファイルの場合
  26. private void analyzeZipFile(File zippedLog) throws IOException {
  27. ZipInputStream zin = new ZipInputStream(new FileInputStream(zippedLog));
  28. ZipEntry entry = null;
  29. while ((entry = zin.getNextEntry()) != null) {
  30. System.out.println("**********" + entry.getName());
  31. analyze(zin);
  32. zin.closeEntry();
  33. }
  34. zin.close();
  35. }
  36. // テキストファイルの場合
  37. private void analyzeTextFile(File textFile) throws IOException {
  38. FileInputStream fis = new FileInputStream(textFile);
  39. analyze(fis);
  40. fis.close();
  41. }
  42. // ログの処理
  43. public void analyze(InputStream in) throws IOException {
  44. BufferedReader br = new BufferedReader(new InputStreamReader(in));
  45. String line = null;
  46. while ((line = br.readLine()) != null) {
  47. System.out.println(line);
  48. // ログの処理
  49. }
  50. }
  51. }

圧縮

  1. // アーカイブ対象ファイル格納 Key:ファイル名、Value:対象ファイル
  2. Map<String, List<File>> zipFileMap = new HashMap<>();
  3. :
  4.  
  5. for(Map.Entry<String, List<File>> zipFileEntity : zipFileMap.entrySet()) {
  6. File zipFile = new File(zipFileEntity.getKey());
  7. List<File> zipContais = zipFileEntity.getValue();
  8. try(ZipOutputStream
  9. zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)))) {
  10. byte[] buf = new byte[1024];
  11. for (File zipContain : zipContais) {
  12. ZipEntry zipEntry = new ZipEntry(zipContain.getName());
  13. zout.putNextEntry(zipEntry);
  14. try(InputStream is = new BufferedInputStream(new FileInputStream(zipContain))) {
  15. @SuppressWarnings("unused")
  16. int size = 0;
  17. while ((size = is.read(buf)) != -1) {
  18. zout.write(buf);
  19. }
  20. }
  21. }
  22. for (File zipContain : zipContais) {
  23. if (zipContain.delete()) {
  24. delFileCnt++;
  25. }
  26. }
  27. } catch (FileNotFoundException e) {
  28. new BatchException(e.getMessage(), e);
  29. } catch (IOException e) {
  30. new BatchException(e.getMessage(), e);
  31. }
  32. }