ファイルをZIP形式で圧縮するサンプルコードです。ZIP形式での圧縮は「java.util.zip.ZipOutputStream」を「FileOutputStream」に連結して行います。
「ZipOutputStream」は「FileOutputStream」など他の出力ストリームに接続して使用します。ZIPファイルに含めるファイルは「ZipEntry」クラスとして、「ZipOutputStream」に追加します。ZipEntryの追加はputNextEntry()メソッドでおこないます。putNextEntry()メソッドでエントリを追加してから、closeEntry()でエントリを閉じるまでの間に、write()メソッドでエントリのファイルの中身を出力ストリームに書き出します。エントリの名前には、ZIPファイルを展開するフォルダからの相対パスを指定します。ZIPファイルの中にディレクトリ構成を作りたい場合は、「A\B.txt」のように上位ディレクトリを含むパスをZipEntryのコンストラクタに指定します。ZipEntryの名前に日本語が含まれていた場合は、文字化けが発生します。これはZipEntryの名称が強制的にUnicodeとして扱われるためです。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFile {
public static void main(String[] args) {
System.out.println("--処理開始--");
if(args.length < 3)
{
System.out.println("コマンドライン引数を指定してください");
return;
}
BufferedInputStream in = null;
ZipOutputStream out = null;
try
{
out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(args[2])));
in = new BufferedInputStream(new FileInputStream(args[0]));
String entryName = new File(args[0]).getName();
out.putNextEntry(new ZipEntry(entryName));
int data = 0;
while( (data = in.read()) != -1 )
{
out.write(data);
}
in.close();
in = null;
out.closeEntry();
in = new BufferedInputStream(new FileInputStream(args[1]));
entryName = new File(args[1]).getName();
out.putNextEntry(new ZipEntry(entryName));
data = 0;
while( (data = in.read()) != -1 )
{
out.write(data);
}
in.close();
in = null;
out.closeEntry();
out.close();
out = null;
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if(in != null)
{
try
{
in.close();
}catch(Exception e){ System.out.println(e); }
}
if(out != null)
{
try
{
out.close();
}catch(Exception e){ System.out.println(e); }
}
}
System.out.println("--処理終了--");
}
}
ちょっと一休み. Javaキーワード並び替えゲーム
画面に表示される文字列を並び替えるとJavaに関連するキーワードになります。ヒントをたよりに並び替えを行ってエンターを押してください。
ユーザ登録をしてログインするとランキングに参加できます。