Back/Spring Java

압축파일 생성

밍꿔 2020. 7. 3. 17:06


반응형

 

public String makeZip(String path, String zipFile, ArrayList<String> fileNames){

		String fileName = zipFile;

		FileOutputStream fout = null;
		ZipOutputStream zout = null;
		try {
			fout = new FileOutputStream(path+zipFile);
			zout = new ZipOutputStream(fout);

			for(int i=0; i < fileNames.size(); i++){

				//본래 파일명 유지, 경로제외 파일압축을 위해 new File로
				ZipEntry zipEntry = new ZipEntry(new File(path+fileNames.get(i)).getName());
				zout.putNextEntry(zipEntry);

				//경로포함 압축
				//zout.putNextEntry(new ZipEntry(sourceFiles.get(i)));

				FileInputStream fin = new FileInputStream(path+fileNames.get(i));
				byte[] buffer = new byte[ZIP_MAX_SIZE];
				int length;

				// input file을 1024바이트로 읽음, zip stream에 읽은 바이트를 씀
				while((length = fin.read(buffer)) > 0){
					zout.write(buffer, 0, length);
				}
				zout.closeEntry();
				fin.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(zout != null){
				try {
					zout.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fout != null){
				try {
					fout.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return fileName;
	}

 

반응형