I am trying to write a java code to save data from a “For Loop” (2d array named “arr”) into a compressed “.txt” file.
FileOutputStream fos = new FileOutputStream(path to zip file); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(fos)); ZipEntry ze = new ZipEntry(path txt file); zipOut.putNextEntry(ze); for (int r = 0; r < 1048577; r++) { for (int c = 0; c < 25; c++) { zipOut.write(arr[r][c] + ","); // how do I write this line? } zipOut.write("n"); // how do I write this line? } zipOut.closeEntry(); zipOut.close();
What piece of code should be added to convert the result into Bytes and then use “ZipOutputStream” to write data into a compressed “.txt” file?
Thanks.
Advertisement
Answer
import java.util.*; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class Main { public static void main(String[] args) { FileOutputStream fos = null; ZipOutputStream zipOut = null; ZipEntry ze = null; try { char[][] arr = {{'a', 'b'}, {'d', 'c'}}; fos = new FileOutputStream("a.zip"); zipOut = new ZipOutputStream(new BufferedOutputStream(fos)); ze = new ZipEntry("out.txt"); zipOut.putNextEntry(ze); StringBuilder sb = new StringBuilder(); for (int r = 0; r < arr.length; r++) { for (int c = 0; c < arr[0].length; c++) { sb.append(arr[r][c]).append(","); } sb.append("n"); // how do I write this line? } zipOut.write(sb.toString().getBytes()); zipOut.closeEntry(); zipOut.close(); } catch (Exception e) { e.printStackTrace(); } } }
maybe this is useful for you