1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JAVA CSVファイルをZIP化しByte配列で管理する方法

Last updated at Posted at 2019-01-14

◆Mainクラス

	public static void main(String[] args) {

		List<File> csvFileList = new ArrayList<File>();
		CsvCreater csvCreater = new CsvCreater();

		for (int i = 0; i < 5; i++) {
			csvFileList.add(csvCreater.createCsv());
		}

		//CSVをZIP化しByte配列化
		ZipFileUtil zipFileUtil = new ZipFileUtil();
		String zipFileName = zipFileUtil.createZip(csvFileList);
		byte[] zipByteArray = zipFileUtil.zipToByteArray(zipFileName);

		//Byte配列をZIPに復元
		EncodeZip encodeZip = new EncodeZip();
		encodeZip.write(zipByteArray);
	}

◆CSVCreater.java

public class CsvCreater {
	private Integer num = 0;

	public CsvCreater() {
		// TODO 自動生成されたコンストラクター・スタブ
	}

	public File createCsv() {
		File csvFile = null;
		CSVWriter csvw = null;
		num += 1;
		try {
			csvFile = createFile(num);
			csvw = new CSVWriter(new FileWriter(csvFile), ",".charAt(0),
					"\"".charAt(0), "\"".charAt(0), "\r\n");

			List<String[]> outStrList = createDate();
			csvw.writeAll(outStrList);

			if (csvw != null) {
				csvw.close();
			}
			System.out.println("処理成功");

		} catch (IOException e) {
			System.out.println("処理失敗");
			e.printStackTrace();
		} finally {
		}
		return csvFile;

	}

	public File createFile(Integer num) {
		Calendar cTime2 = Calendar.getInstance();
		String csvFileName = "tmp/csvFile" + cTime2.get(Calendar.SECOND) + "_" + num + ".csv";
		num = num + 1;
		return new File(csvFileName);
	}

	public List<String[]> createDate() {
		List<String[]> outDateList = new ArrayList<String[]>();
		String[] outStr = new String[100];
		Integer numnum;
		for (int k = 0; k < 5; k++) {
			for (int j = 0; j < 100; j++) {
				numnum = j * k;
				outStr[j] = numnum.toString();
			}
			outDateList.add(outStr);
		}
		return outDateList;
	}

}

◆ZipファイルUtillクラス

package csv;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileUtil {

	public String createZip(List<File> fileList) {
		ZipOutputStream zos = null;
		Calendar cTime = Calendar.getInstance(); //[1]
		String zipFileName = "tmp/zipfile" + cTime.get(Calendar.SECOND) + ".zip";
		File file = new File(zipFileName);

		try {
			zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
			createZip2(zos, fileList);

			fileSizeCheck(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return zipFileName;
	}

	public void createZip2(ZipOutputStream zos, List<File> fileList) throws IOException {
		byte[] buf = new byte[1024];
		InputStream is = null;
		try {
			for (File file : fileList) {
				ZipEntry entry = new ZipEntry(file.getName());
				zos.putNextEntry(entry);
				is = new BufferedInputStream(new FileInputStream(file));
				int len = 0;
				while ((len = is.read(buf)) != -1) {
					zos.write(buf, 0, len);
				}
			}

			is.close();
			zos.closeEntry();
		} catch (IOException e) {
			e.printStackTrace();
		}
		zos.close();

	}

	public void fileSizeCheck(File file) {
		long fileSize = file.length() / 1024;
		if (fileSize > 0) {
			System.out.println("ファイル:" + file.getName());
			System.out.println("ファイルサイズ:" + fileSize + "KB");

		} else {
			System.out.println("不正ファイルです:1KB");

		}

	}

	public byte[] zipToByteArray(String zipFileName) {
		File file = new File(zipFileName);
		try {
			InputStream inputStream = new FileInputStream(file);

			return getBytes(inputStream);

		} catch (FileNotFoundException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
		return null;

	}

	/**
	* InputStreamをバイト配列に変換する
	*
	* @param is
	* @return バイト配列
	*/
	public byte[] getBytes(InputStream is) {
		// byte型の配列を出力先とするクラス。
		// 通常、バイト出力ストリームはファイルやソケットを出力先とするが、
		// ByteArrayOutputStreamクラスはbyte[]変数、つまりメモリを出力先とする。
		ByteArrayOutputStream b = new ByteArrayOutputStream();
		OutputStream os = new BufferedOutputStream(b);
		int c;
		try {
			while ((c = is.read()) != -1) {
				os.write(c);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// 書き込み先はByteArrayOutputStreamクラス内部となる。
		// この書き込まれたバイトデータをbyte型配列として取り出す場合には、
		// toByteArray()メソッドを呼び出す。
		return b.toByteArray();
	}
}
```

EncodeZip

```java
package csv.day0114;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class EncodeZip {

	public EncodeZip() {
		// TODO 自動生成されたコンストラクター・スタブ
	}

	public void write(byte[] byteData) {

		File outputImageFile = new File("tmp/outfile2.zip");
		InputStream inputStream = new ByteArrayInputStream(byteData);

		OutputStream os = null;
		try {
			os = new BufferedOutputStream(new FileOutputStream(outputImageFile));
			int c;
			while ((c = inputStream.read()) != -1)
				os.write(c);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
```

ディレクトリ削除再起的

```java
	public void dirDelete(File TestFile) {
		if (TestFile.exists()) {

			//ファイル存在チェック
			if (TestFile.isFile()) {
				//存在したら削除する
				if (TestFile.delete()) {
					System.out.println("ファイル削除:" + TestFile.getName());
					this.j++;
				} else {
					System.out.println("ファイル存在しない:" + TestFile.getName());
				}
				//対象がディレクトリの場合
			} else if (TestFile.isDirectory()) {

				//ディレクトリ内の一覧を取得
				File[] files = TestFile.listFiles();

				//存在するファイル数分ループして再帰的に削除
				for (int i = 0; i < files.length; i++) {
					dirDelete(files[i]);
				}
				System.out.println("削除対象:" + files.length + " 削除数:" + this.j);

			}
		} else {
			System.out.println("ディレクトリが存在しない");
		}
	}
```
1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?