** JAVAでファイルをZIP圧縮する [#h0e4102a]

#setlinebreak(on);

java.util.zip パッケージを使用してファイルをZIP圧縮する

 package test_java;
 
 import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.UnsupportedEncodingException;
 import java.util.zip.*;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 public class TestZip extends HttpServlet {
 
 	public void doGet(HttpServletRequest request, HttpServletResponse response)
 	throws IOException, ServletException {
 		process(request, response);
 	}
 
 	public void doPost(HttpServletRequest request, HttpServletResponse response)
 		throws IOException, ServletException {
 		process(request, response);
 	}
 
 	protected void process(HttpServletRequest request, HttpServletResponse response)
 		throws IOException, ServletException {
 
 		String zipFileDir  = "/home/hoge";
 		String zipFileName = "files.zip";
 		String zipFilePath = zipFileDir + "/" + zipFileName;
 		
 		String[] targetFiles = {"/home/hoge/file1.txt","/home/hoge/file2.txt","/home/hoge/file3.txt"};
 		
 		OutputStream out = null;
 		FileInputStream in = null;
 		try {
 			// ZIPファイルの作成
 			createZip(zipFilePath , targetFiles);
 
 			// ファイル名のエンコード
 			zipFileName = encodeFileName(zipFileName);
 			
 			// ZIPファイルのダウンロード
 			response.setContentType("application/octet-stream; charset=\"Windows-31J\"");
 			response.setHeader("Content-Disposition", "attachment; filename=\""+ zipFileName + "\"");
 
 			out = response.getOutputStream(); 
 			in = new FileInputStream(zipFilePath);
 			int c;
 			while ((c = in.read()) != -1) { 
 				out.write(c);
 			}
 		} catch (IOException e) {
 			
 		} finally {
 
 			if (out != null) {
 				try {
 					out.close();
 				} catch (IOException e) {
 				}
 			}
 
 			if (in != null) {
 				try {
 					in.close();
 					in = null;
 				} catch (IOException e) {
 				}
 			}
 		}
 
 		// 作業用ファイルを削除
 		try {
 			(new File(zipFilePath)).delete();
 			for (int i = 0; i < targetFiles.length; i++) {
 				(new File(targetFiles[i])).delete();
 			}
 		} catch (Exception e){
 		}
 	}
 
 	/**
 	 * targetFilesをZIP圧縮してzipFileに出力する。
 	 * @param zipFile ZIP出力ファイル名
 	 * @param targetFiles 入力ファイル名(ディレクトリ)配列
 	 * @throws IOException 入出力例外
 	 */
 	public static void createZip(String zipFile, String[] targetFiles)
 	    throws IOException {
 	
 		ZipOutputStream out =
 			new ZipOutputStream(new FileOutputStream(zipFile));
 		for (int i = 0; i < targetFiles.length; i++) {
 			File file = new File(targetFiles[i]);
 			int deleteLength = file.getPath().length() - file.getName().length();
 			createZip(out, file, deleteLength);
 		}
 		out.close();
 	}
 	
 	/**
 	 * targetFileをoutのZIPエントリへ出力する。
 	 * @param out ZIP出力先
 	 * @param targetFile 入力ファイル名(ディレクトリ)
 	 * @throws IOException 入出力例外
 	 */
 	private static void createZip(ZipOutputStream out, File targetFile, int deleteLength)
 	    throws IOException {
 	
 		if (targetFile.isDirectory()) {
 			File[] files = targetFile.listFiles();
 			for (int i = 0; i < files.length; i++) {
 				createZip(out, files[i], deleteLength);
 			}
 		} else {
 			ZipEntry target = new ZipEntry(getEntryPath(targetFile, deleteLength));
 			out.putNextEntry(target);
 			byte buf[] = new byte[1024];
 			int count;
 			BufferedInputStream in =
 			    new BufferedInputStream(new FileInputStream(targetFile));
 			while ((count = in.read(buf, 0, 1024)) != -1) {
 				out.write(buf, 0, count);
 			}
 			in.close();
 			out.closeEntry();
 			in = null;
 			out = null;
 		}
 	}
 
 	/**
 	 * ZIPエントリパスを返す。
 	 * @param file ZIPエントリ対象ファイル
 	 * @return ZIPエントリのパス
 	*/
 	private static String getEntryPath(File file, int deleteLength) {
 		return file.getPath().replaceAll("\\\\", "/").substring(deleteLength);
 	}
 
 	/**
 	 * ファイル名をURLエンコードする
 	 * @param fileName
 	 * @return エンコードされたファイル名
 	 */
 	private String encodeFileName(String fileName) {
 		
 		try {
 			fileName = new String(fileName.getBytes("Shift_JIS"), "ISO-8859-1");
 		} catch (UnsupportedEncodingException e){
 		}
 
 		return fileName;
 	}
 }


トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS