我有一个需要压缩的文件列表,我正在使用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();
}
}
}
有没有办法让拉链文件只读?