How to ZIP a JAVA CSV file and manage it in a Byte array

◆ Main class

	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());
		}

		//Convert CSV to Byte array
		ZipFileUtil zipFileUtil = new ZipFileUtil();
		String zipFileName = zipFileUtil.createZip(csvFileList);
		byte[] zipByteArray = zipFileUtil.zipToByteArray(zipFileName);

		//Restore Byte array to ZIP
		EncodeZip encodeZip = new EncodeZip();
		encodeZip.write(zipByteArray);
	}

◆CSVCreater.java

public class CsvCreater {
	private Integer num = 0;

	public CsvCreater() {
		//TODO auto-generated constructor stub
	}

	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("Successful processing");

		} catch (IOException e) {
			System.out.println("Processing failure");
			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 file Utill class

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:" + file.getName());
			System.out.println("file size:" + fileSize + "KB");

		} else {
			System.out.println("Illegal file: 1KB");

		}

	}

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

			return getBytes(inputStream);

		} catch (FileNotFoundException e) {
			//TODO auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	/**
	*Convert InputStream to byte array
	*
	* @param is
	* @return byte array
	*/
	public byte[] getBytes(InputStream is) {
		//A class whose output destination is a byte type array.
		//Normally, the byte output stream is output to a file or socket,
		//ByteArrayOutputStream class is byte[]The output destination is a variable, that is, memory.
		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();
				}
			}
		}

		//The write destination is inside the ByteArrayOutputStream class.
		//When extracting this written byte data as a byte type array,
		// toByteArray()Call the method.
		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 auto-generated constructor stub
	}

	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();
				}
			}
		}
	}
}
```

 ◆ Directory deletion (recursive)

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

			//File existence check
			if (TestFile.isFile()) {
				//Delete if it exists
				if (TestFile.delete()) {
					System.out.println("File deletion:" + TestFile.getName());
					this.j++;
				} else {
					System.out.println("File does not exist:" + TestFile.getName());
				}
				//If the target is a directory
			} else if (TestFile.isDirectory()) {

				//Get the list in the directory
				File[] files = TestFile.listFiles();

				//Loop through the number of existing files and delete recursively
				for (int i = 0; i < files.length; i++) {
					dirDelete(files[i]);
				}
				System.out.println("Target to be deleted:" + files.length + "Number of deletions:" + this.j);

			}
		} else {
			System.out.println("Directory does not exist");
		}
	}
```


Recommended Posts

How to ZIP a JAVA CSV file and manage it in a Byte array
How to convert a file to a byte array in Java
Gzip-compress byte array in Java and output to file
How to convert A to a and a to A using AND and OR in Java
How to make a Java array
Convert a Java byte array to a string in hexadecimal notation
How to develop and register a Sota app in Java
How to read a file and treat it as standard input
How to test a private method in Java and partially mock that method
The story of forgetting to close a file in Java and failing
To create a Zip file while grouping database search results in Java
How to record JFR (Java Flight Recorder) and output a dump file
[Java] [For beginners] How to insert elements directly in a 2D array
How to display a web page in Java
<java> Read Zip file and convert directly to string
How to create a Java environment in just 3 seconds
How to jump from Eclipse Java to a SQL file
Write a class in Kotlin and call it in Java
How to handle TSV files and CSV files in Ruby
How to Git manage Java EE projects in Eclipse
How to save a file with the specified extension under the directory specified in Java to the list
How to initialize Java array
Create a Java Servlet and JSP WAR file to deploy to Apache Tomcat 9 in Gradle
How to request a CSV file as JSON with jMeter
How to read your own YAML file (*****. Yml) in Java
Assign a Java8 lambda expression to a variable and reuse it
[Java] I want to convert a byte array to a hexadecimal number
How to change a string in an array to a number in Ruby
Read WAV data as a byte array in Android Java
[Java] How to convert a character string from String type to byte type
How to store a string from ArrayList to String in Java (Personal)
What happened in "Java 8 to Java 11" and how to build an environment
How to call and use API in Java (Spring Boot)
Java Language Feature and How it Produced a Subtle Bug
How to add the same Indexes in a nested array
How to simulate uploading a post-object form to OSS in Java
Differences in how to handle strings between Java and Perl
How to write comments in the schema definition file in GraphQL Java and reflect them in GraphQL and GraphQL Playground
How to make a Java container
How to learn JAVA in 7 days
Unzip the zip file in Java
[Java] How to create a folder
Log output to file in Java
How to use classes in Java?
How to name variables in Java
How to concatenate strings in java
How to make a jar file with no dependencies in Maven
How to implement a job that uses Java API in JobScheduler
How to create a new Gradle + Java + Jar project in Intellij 2016.03
How to automatically operate a screen created in Java on Windows
How to load a Spring upload file and view its contents
Cast an array of Strings to a List of Integers in Java
Read items containing commas in a CSV file without splitting (Java)
Sample to read and write LibreOffice Calc fods file in Java 2021
How to encrypt and decrypt with RSA public key in Java
How to get the length of an audio file in java
[Java] How to search for a value in an array (or list) with the contains method
Convert Excel to Blob with java, save it, read it from DB and output it as a file!
[Xcode] How to add a README.md file
How to make a Java calendar Summary
When seeking multiple in a Java array