如何将 "For Loop" 中的数据保存到压缩的“.txt”文件中

How to save data from a "For Loop" into a compressed ".txt" file

我正在尝试编写 java 代码以将“For 循环”(名为“arr”的二维数组)中的数据保存到压缩的“.txt”文件中。

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

将结果转换为字节,然后使用“ZipOutputStream”将数据写入压缩的“.txt”文件,应该添加什么代码?

谢谢。

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

    }
}

也许这对你有用

所以,我“最”关心的是如何“读”回数据,写入数据实际上相对容易。

下面是一个“基本”工作,使用几个 StringJoiners 生成一个可以写入文件的 String 和一个有点复杂的过程来解压缩它。

这里的问题是,限制因素(至少对我而言)是在开始重建文件之前需要阅读文件的全部内容。

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.StringJoiner;
import java.util.zip.DataFormatException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class Test {

    public static void main(String[] args) throws IOException, DataFormatException {
        File targetFile = new File("Test.dat");

        int[][] data = new int[][]{
            {0, 1, 2, 3, 4, 5},
            {6, 7, 8, 9, 10, 11}
        };

        StringJoiner outterJoiner = new StringJoiner("\n");
        for (int[] outter : data) {
            StringJoiner innerJoiner = new StringJoiner(",");
            for (int value : outter) {
                innerJoiner.add(Integer.toString(value));
            }
            outterJoiner.add(innerJoiner.toString());
        }

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(targetFile))) {
            ZipEntry zipEntry = new ZipEntry("master");
            zos.putNextEntry(zipEntry);
            zos.write(outterJoiner.toString().getBytes());
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(targetFile)); ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ZipEntry zipEntry = zis.getNextEntry();
            if (zipEntry != null) {
                byte[] buffer = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = zis.read(buffer)) != -1) {
                    baos.write(buffer, 0, bytesRead);
                }

                String contents = new String(baos.toByteArray());
                System.out.println(contents);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

我想知道您是否使用 ZipEntry 而不是依赖 \n 作为分隔符,这样您就可以一次处理每一“行”数据...

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.StringJoiner;
import java.util.zip.DataFormatException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class Test {

    public static void main(String[] args) throws IOException, DataFormatException {
        File targetFile = new File("Test.dat");

        int[][] data = new int[][]{
            {0, 1, 2, 3, 4, 5},
            {6, 7, 8, 9, 10, 11}
        };

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(targetFile))) {
            for (int index = 0; index < data.length; index++) {
                int[] values = data[index];
                ZipEntry zipEntry = new ZipEntry("Values-" + index);
                zos.putNextEntry(zipEntry);
                StringJoiner joiner = new StringJoiner(",");
                for (int value : values) {
                    joiner.add(Integer.toString(value));
                }
                zos.write(joiner.toString().getBytes());
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(targetFile))) {
            ZipEntry zipEntry = null;
            while ((zipEntry = zis.getNextEntry()) != null) {
                System.out.println(zipEntry.getName());
                try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                    byte[] buffer = new byte[1024];
                    int bytesRead = -1;
                    while ((bytesRead = zis.read(buffer)) != -1) {
                        baos.write(buffer, 0, bytesRead);
                    }

                    String contents = new String(baos.toByteArray());
                    System.out.println(contents);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

打印出...

Values-0
0,1,2,3,4,5
Values-1
6,7,8,9,10,11

现在,显然,您可能不知道需要多少行,作为第一个示例,一个简单的 String#split 会告诉您。 (您可以预先阅读每个条目,但那是双重浸渍)

is it possible to have ZipOutputStream save "contents" into a compressed ".txt" file called "Compressed file.txt" in a zip file "C:/Users/Username/Documents/Compressed folder.zip" ?

这完全取决于您,如果您不再关心 reading/parse 文件,则可以大大减少流程(工作量和复杂性)。

因此,下面的示例将一次写入一行内容,因此您只需创建一行文本,然后将其写入 ZipEntryStringJoiner 使这个过程变得非常简单

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.StringJoiner;
import java.util.zip.DataFormatException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Test {

    public static void main(String[] args) throws IOException, DataFormatException {
        File targetFile = new File("Compressed.zip");

        int[][] data = new int[][]{
            {0, 1, 2, 3, 4, 5},
            {6, 7, 8, 9, 10, 11}
        };

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(targetFile))) {
            ZipEntry zipEntry = new ZipEntry("Compressed.txt");
            zos.putNextEntry(zipEntry);
            for (int[] outter : data) {
                StringJoiner joiner = new StringJoiner(",", "", "\n");
                for (int value : outter) {
                    joiner.add(Integer.toString(value));
                }
                zos.write(joiner.toString().getBytes());
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

这里有一个非常basic/simplyfied的想法:

var zos = new ZipOutputStream(new FileOutputStream("text.zip"));
try (zos) {
    var entry = new ZipEntry("test.txt");
    zos.putNextEntry(entry);

    var value = 12345; // just an example, should come from array/loop
    
    zos.write(Integer.toString(value).getBytes());
    zos.write(",".getBytes());
    
    zos.write("\n".getBytes());
    
    zos.closeEntry();
}

您需要添加循环。

注 1:",".getBytes(...)"\n"...
使用 variables/constants 注 2:使用 getBytes() 的默认系统字符集,要使用特定的字符集,请使用 getBytes(StandardCharsets.UTF_8)