我一直在使用此代码将目录压缩到磁盘C中,在大学实验室的计算机中,程序确实创建了exp.zip而没有任何问题,但在我的计算机中却无法实现。我将磁盘C所有权更改为我的实际会话,允许所有权限,并以管理员身份运行程序(.jar文件)但未成功。我认为这不是一个代码问题,因为它在实验室的计算机上运行Windows和Linux(当然改变路径)都有效,但我仍然要把它粘贴在这里,这样你就可以知道我想要的是什么做:
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 Compress {
public static void zipDirectory(String dir, String zipfile)
throws IOException, IllegalArgumentException {
File d = new File(dir);
if (!d.isDirectory())
throw new IllegalArgumentException("Not directory: "+ dir);
String[] entries = d.list();
byte[] buffer = new byte[4096];
int bytesRead;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int i = 0; i < entries.length; i++) {
File f = new File(d, entries[i]);
if (f.isDirectory())
continue;
FileInputStream in = new FileInputStream(f);
ZipEntry entry = new ZipEntry(f.getPath());
out.putNextEntry(entry);
while ((bytesRead = in.read(buffer)) != -1)
out.write(buffer, 0, bytesRead);
in.close();
}
out.close();
}
public static void compress() throws IOException {
String from = "C:\\exp\\"; //path windows
File f = new File(from);
if(!f.exists())
f.mkdir();
Compress.zipDirectory(from, "C:\\exp.zip"); //path windows
}
}
提前致谢!