[英]Unable to make folders to zip files using java?
在这里,我在“图书”文件夹中有文件夹(“书”)结构,我有一个名为“物理,化学,科学,英语”的文件夹。我将“图书”文件夹作为zipDeleteFile传递,但是在所有文件夹中,必须将其转换为与physics.zip相同的文件夹(“书”) ,chemistry.zip,science.zip,english.zip。但是此代码无法正常工作。
“
public void foldertToZip(File zipDeleteFile) {
//System.out.println(zipDeleteFile);
File directoryToZip = zipDeleteFile;
List<File> fileList = new ArrayList<File>();
//System.out.println("---Getting references to all files in: " + directoryToZip.getCanonicalPath());
getAllFiles(directoryToZip, fileList);
//System.out.println("---Creating zip file");
writeZipFile(directoryToZip, fileList);
//System.out.println("---Done");
}
public static void getAllFiles(File dir, List<File> fileList) {
try {
File[] files = dir.listFiles();
for (File file : files) {
fileList.add(file);
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
getAllFiles(file, fileList);
} else {
System.out.println(" file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeZipFile(File directoryToZip, List<File> fileList) {
try {
try (FileOutputStream fos = new FileOutputStream(directoryToZip.getName() + ".zip")) {
ZipOutputStream zos = new ZipOutputStream(fos);
for (File file : fileList) {
if (!file.isDirectory()) { // we only zip files, not directories
addToZip(directoryToZip, file, zos);
}
}
zos.close();
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException,
IOException {
try (FileInputStream fis = new FileInputStream(file)) {
String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
file.getCanonicalPath().length());
System.out.println("Writing '" + zipFilePath + "' to zip file");
ZipEntry zipEntry = new ZipEntry(zipFilePath);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
}
}`'
最初,我将zipDeleteFile作为C:\\ Books传递给Books,我拥有所有物理,英语,科学文件夹,这些文件夹必须转换为同一根文件夹(Books)中的zip文件。
因此,基本上,您希望将Books
文件夹中的每个目录压缩为自己的zip文件。 您可以通过几种方法来执行此操作,但最简单的方法可能是更改调用文件foldertToZip
因此,而不是(类似)...
foldertToZip(new File("C:\\Books"));
你可以做类似...
for (File file : new File("C:\\Books").listFiles()) {
if (file.isDirectory()) {
foldertToZip(file);
}
}
这将导致将Books
中的每个目录添加到其自己的zip文件中,该文件将位于Books
您可能需要进行的另一项更改是...
public static void writeZipFile(File directoryToZip, List<File> fileList) {
try {
//try (FileOutputStream fos = new FileOutputStream(directoryToZip.getName() + ".zip")) {
File path = directoryToZip.getParentFile();
File zipFile = new File(path, directoryToZip.getName() + ".zip");
try (FileOutputStream fos = new FileOutputStream(zipFile)) {
这将在要压缩的目录(即Books
目录)的父目录内创建zip文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.