如何制作压缩文件只读

时间:2016-07-20 14:32:36

标签: java

我有一个需要压缩的文件列表,我正在使用ZipOutputStream。

当我获取文件时,我将每个文件设置为只读。 (我尝试过使用file.setWritable(false)和file.setReadOnly())

原始文件已更改,但保存在zip中的文件尚未就绪。我猜这是因为我必须使用FileInputStream将每个文件添加到zip中。

为了测试我正在使用我在网上找到的示例代码。

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

public class TestZip {

    public static void main(String[] args) {
        byte[] buffer = new byte[1024];

        try {

            File zipFile = new File("C:\\Users\\thop\\Desktop\\Test\\test.txt");
            zipFile.setWritable(false);

            FileOutputStream fos = new FileOutputStream("C:\\Users\\thop\\Desktop\\Test\\MyFile.zip");
            ZipOutputStream zos = new ZipOutputStream(fos);
            ZipEntry ze = new ZipEntry(zipFile.getAbsolutePath());
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(zipFile.getAbsolutePath());
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
            zos.closeEntry();
            zos.close();
            System.out.println("Done");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

有没有办法让拉链文件只读?

实施例: 我保存的文件被设置为只读。 File that gets zipped

当我将test.txt保存在zip文件中并将其解压缩到MyFile文件夹中时,它不再是只读的。 Explanation

1 个答案:

答案 0 :(得分:0)

ZipOutputStream不使用保存的文件,但会读取它们然后拉链它们。

如果您想使用您有权访问的文件并使其保持原样,可以使用zip4j