【发布时间】:2014-07-23 06:52:28
【问题描述】:
在这里,我在 Books 文件夹中有文件夹(Books)结构,我有名为 Physics、chemistry、science、english 的文件夹。我将 Books 文件夹作为 zipDeleteFile 传递,但在所有文件夹内必须转换为同一个文件夹(Books) 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 我有所有物理、英语、科学文件夹,这些文件夹必须转换为同一根文件夹(书籍)中的 zip 文件。
【问题讨论】:
-
请不要默默吞下异常。
-
@MadProgrammer,它不会转换为 zip 文件。
-
对我来说很好。我可以在 Windows 资源管理器中查看文件的内容,这总是一个好兆头
-
@MadProgrammer,转换后不显示为 zip 文件。我在这里做错了。
-
“不显示为 zip 文件”是什么意思?你的代码创建了一个 zip,我可以通过 Windows 读取它的内容