Javaで指定したディレクトリ下にあるファイルをファイルの更新日時を条件に新しいディレクトリにコピーし、圧縮するプログラムを作っています。
圧縮するところまでは出来たのですが、実行してみるとzipファイルのみ作成されて中身が空のままファイルがコピー出来ていません。
ちなみにzip化は以下のサイトを参考に実装しました。
Java ZIP圧縮する方法 ディレクトリ指定やファイル指定 - ZipEntry・ZipOutputStream
mainのコード
java
1import java.io.File; 2import java.io.IOException; 3import java.nio.file.Files; 4import java.nio.file.Path; 5import java.nio.file.Paths; 6import java.text.SimpleDateFormat; 7import java.util.Arrays; 8import java.util.Calendar; 9 10public class a { 11 public static void main(String[] args) { 12//////////保存先のディレクトリの作成 13 // Windows Vista 以降での仕様(UAC)でシステムルートドライブ(C:\)には書き込めない(管理者権限の昇格が必要)のでとりあえずD:に作成 14 //"D:\test"にするとファイル名が\testになる 15 //Fileクラスのオブジェクトを生成 16 File newdir = new File("D:\test\sub"); 17 18 if (newdir.mkdir()){ 19 System.out.println("ディレクトリの作成に成功しました"); 20 }else{ 21 System.out.println("ディレクトリの作成に失敗しました"); 22 } 23 24 25/////////ファイルのコピー 26 //Fileクラスのオブジェクトを作成 27 File dir = new File("D:\logs\lsm-application\20190508"); 28 //listFiles:指定したディレクトリに含まれるファイルやディレクトリを配列で返す 29 File[] list = dir.listFiles(); 30 31 //nullチェック 32 //listfilesは指定したパス名がディレクトリを示さない場合や入出力エラーが発生した場合にnullを返す 33 //null状態のままオブジェクト配列を参照するとjava.lang.NullPointerExceptionの例外が発生 34 if(list != null) { 35 //読み込んだファイルやディレクトリの数を表示 36 System.out.println(list.length); 37 } else { 38 System.out.println("null"); 39 } 40 41 //最終更新日時表示書式 42 //SimpleDateFormat(String)で指定されたパターン、デフォルトのロケール、日付フォーマット記号を持つ、オブジェクトを生成 43 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 44 45 // ファイルの最終更新日時(タイムスタンプ)を取得 46 // 1970年1月1日0時0分0秒からの経過ミリ秒 47 //long lastModified = list.lastModified(); 48 49 //最終更新日時書式整形 50 //String lastModifiedStr = sdf.format(lastModified); 51 52 //表示 53 //System.out.println(lastModifiedStr); 54 55 for (int i=0; i<list.length; i++) { 56 57 // ファイルの最終更新日時(タイムスタンプ)を取得 58 // 1970年1月1日0時0分0秒からの経過ミリ秒 59 long lastModified = list[i].lastModified(); 60 61 //最終更新日時書式整形 62 //String lastModifiedStr = sdf.format(lastModified); 63 64 System.out.println(list[i]); 65 //System.out.println(lastModifiedStr); 66 67 //ファイルのコピー 68 Path sourcePath = Paths.get(list[i].getPath()); 69 Path destinationPath = Paths.get("D:\test\sub\" + list[i].getName() + ".txt"); 70 71 //あsファイルの更新日時をlong型からCalendar型に変換 72 Calendar source = Calendar.getInstance(); 73 //setTimeInMillis:Calendar の現在時刻を、指定された long 値から設定 74 source.setTimeInMillis(lastModified); 75 76 //CalendarクラスやDateクラスは月を0~11で表すため一カ月ずれる!! 77 //日時の設定 78 Calendar start = Calendar.getInstance(); 79 start.set(2019, 4, 8, 06, 00, 00); 80 81 //日時の設定 82 Calendar end = Calendar.getInstance(); 83 end.set(2019, 4, 8, 12, 00, 00); 84 85 //cal1.compareTo(cal2) 86 //同じなら0、cal1過去・cal2(引数)が未来なら負数1、cal1が未来なら正数を返す 87 int diff1 = source.compareTo(start); 88 int diff2 = source.compareTo(end); 89 90 if(diff1 > 0 && diff2 < 0) { 91 //ファイルのコピー 92 try { 93 Files.copy(sourcePath,destinationPath); 94 } catch (IOException e) { 95 e.printStackTrace(); 96 } 97 } 98 99 100 } 101 102 ZipCompressUtils.compressDirectory("D:\test\subzip.zip", "D:\test\sub\"); 103 104 105 } 106}
mainクラス単体では最後の
ZipCompressUtils.compressDirectory("D:\test\subzip.zip", "D:\test\sub");
の行を追加する前はうまく実行できました。
ZipCompressUtilsクラスのコード
java
1package com.en.saka.util; 2 3import java.io.BufferedInputStream; 4import java.io.File; 5import java.io.FileInputStream; 6import java.io.FileOutputStream; 7import java.util.ArrayList; 8//import org.apache.tools.zip.ZipEntry; 9import java.util.zip.ZipEntry; 10import java.util.zip.ZipOutputStream; 11//import org.apache.tools.zip.ZipOutputStream; 12 13/** 14 * ZipCompressUtils は、ZIP 圧縮をおこなう上で利便性の高い機能を提供します。 15 * 16 * @author saka-en. 17 * @version $Revision: 1.0 $ $Date: 2013.10.24 $ $Description: 新規作成 $ 18 */ 19public class ZipCompressUtils { 20 21 /** 22 * 指定されたディレクトリ内のファイルを ZIP アーカイブし、指定されたパスに作成します。 23 * デフォルト文字コードは Shift_JIS ですので、日本語ファイル名も対応できます。 24 * 25 * @param fullPath 圧縮後の出力ファイル名をフルパスで指定 ( 例: C:/sample.zip ) 26 * @param directory 圧縮するディレクトリ ( 例; C:/sample ) 27 * @return 処理結果 true:圧縮成功 false:圧縮失敗 28 */ 29 public static boolean compressDirectory( String filePath, String directory ) { 30 File baseFile = new File(filePath); 31 File file = new File(directory); 32 ZipOutputStream outZip = null; 33 try { 34 // ZIPファイル出力オブジェクト作成 35 outZip = new ZipOutputStream(new FileOutputStream(baseFile)); 36 archive(outZip, baseFile, file); 37 } catch ( Exception e ) { 38 // ZIP圧縮失敗 39 return false; 40 } finally { 41 // ZIPエントリクローズ 42 if ( outZip != null ) { 43 try { outZip.closeEntry(); } catch (Exception e) {} 44 try { outZip.flush(); } catch (Exception e) {} 45 try { outZip.close(); } catch (Exception e) {} 46 } 47 } 48 return true; 49 } 50 51 /** 52 * 指定された ArrayList のファイルを ZIP アーカイブし、指定されたパスに作成します。 53 * デフォルト文字コードは Shift_JIS ですので、日本語ファイル名も対応できます。 54 * 55 * @param filePath 圧縮後のファイル名をフルパスで指定 ( 例: C:/sample.zip ) 56 * @param fileList 圧縮するファイルリスト ( 例; {C:/sample1.txt, C:/sample2.txt} ) 57 * @return 処理結果 true:圧縮成功 false:圧縮失敗 58 */ 59 public static boolean compressFileList( String filePath, ArrayList<String> fileList ) { 60 61 ZipOutputStream outZip = null; 62 File baseFile = new File(filePath); 63 try { 64 // ZIPファイル出力オブジェクト作成 65 outZip = new ZipOutputStream(new FileOutputStream(baseFile)); 66 // 圧縮ファイルリストのファイルを連続圧縮 67 for ( int i = 0 ; i < fileList.size() ; i++ ) { 68 // ファイルオブジェクト作成 69 File file = new File((String)fileList.get(i)); 70 archive(outZip, baseFile, file, file.getName(), "Shift_JIS"); 71 } 72 } catch ( Exception e ) { 73 // ZIP圧縮失敗 74 return false; 75 } finally { 76 // ZIPエントリクローズ 77 if ( outZip != null ) { 78 try { outZip.closeEntry(); } catch (Exception e) {} 79 try { outZip.flush(); } catch (Exception e) {} 80 try { outZip.close(); } catch (Exception e) {} 81 } 82 } 83 return true; 84 } 85 86 /** 87 * ディレクトリ圧縮のための再帰処理 88 * 89 * @param outZip ZipOutputStream 90 * @param baseFile File 保存先ファイル 91 * @param file File 圧縮したいファイル 92 */ 93 private static void archive(ZipOutputStream outZip, File baseFile, File targetFile) { 94 if ( targetFile.isDirectory() ) { 95 File[] files = targetFile.listFiles(); 96 for (File f : files) { 97 if ( f.isDirectory() ) { 98 archive(outZip, baseFile, f); 99 } else { 100 if ( !f.getAbsoluteFile().equals(baseFile) ) { 101 // 圧縮処理 102 archive(outZip, baseFile, f, f.getAbsolutePath().replace(baseFile.getParent(), "").substring(1), "Shift_JIS"); 103 } 104 } 105 } 106 } 107 } 108 109 /** 110 * 圧縮処理 111 * 112 * @param outZip ZipOutputStream 113 * @param baseFile File 保存先ファイル 114 * @param targetFile File 圧縮したいファイル 115 * @parma entryName 保存ファイル名 116 * @param enc 文字コード 117 */ 118 private static boolean archive(ZipOutputStream outZip, File baseFile, File targetFile, String entryName, String enc) { 119 // 圧縮レベル設定 120 outZip.setLevel(5); 121 122 // 文字コードを指定 123 outZip.setEncoding(enc); 124 try { 125 126 // ZIPエントリ作成 127 outZip.putNextEntry(new ZipEntry(entryName)); 128 129 // 圧縮ファイル読み込みストリーム取得 130 BufferedInputStream in = new BufferedInputStream(new FileInputStream(targetFile)); 131 132 // 圧縮ファイルをZIPファイルに出力 133 int readSize = 0; 134 byte buffer[] = new byte[1024]; // 読み込みバッファ 135 while ((readSize = in.read(buffer, 0, buffer.length)) != -1) { 136 outZip.write(buffer, 0, readSize); 137 } 138 // クローズ処理 139 in.close(); 140 // ZIPエントリクローズ 141 outZip.closeEntry(); 142 } catch ( Exception e ) { 143 // ZIP圧縮失敗 144 return false; 145 } 146 return true; 147 } 148}
ZipCompressUtilsクラスについて以下のようなエラーメッセージエラーメッセージが出ます。
1.1行目:package com.en.saka.util;の部分
エラーメッセージ「宣言されたパッケージが予想されたパッケージ""に一致しません」
2.19行目:public class ZipCompressUtils { の部分
エラーメッセージ「型ZipCompressUtilsは既に宣言されています」
3.123行目:outZip.setEncoding(enc);
エラーメッセージ「メソッドsetEncoding(String)は型ZipOutputStreamで未定義です」
2については他にZipCompressUtilsクラスを作成したか探してみましたが見当たりませんでした。
その他色々サイトを見てみたんですが、javaに慣れておらずサイトに記載されている内容がいまいちわかりませんでした。
質問してばかりで申し訳ないのですがどなたか原因と対処法についてご教示頂けると幸いです。
回答1件
あなたの回答
tips
プレビュー