【发布时间】:2022-01-02 16:31:19
【问题描述】:
我正在尝试将数百个 zip 格式的文件解压缩到另一个文件夹中。我通过打开每个 zip 并读取文本文件来获得新文件夹的正确名称。将其保存为路径/字符串。
上次我使用它时,我设法创建了所有具有正确名称的新文件夹,可惜拉链没有提取到它们中。 (下面的代码是我的第 3 次或第 4 次尝试,所以我不再获得正确的文件夹。目前,我收到一个错误,指出新文件夹的路径名不存在。
公共类主{
public static void main(String[] args) throws IOException {
File dir = new File("mods/");
File[] zips = dir.listFiles();
for (File f : zips) {
ZipFile zipFile = new ZipFile(f);
Enumeration<?> enu = zipFile.entries();
while (enu.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enu.nextElement();
String name = zipEntry.getName();
long size = zipEntry.getSize();
long compressedSize = zipEntry.getCompressedSize();
System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n",
name, size, compressedSize);
// Do we need to create a directory ?
File file = new File(getNewPath(f) + name);
if (name.endsWith("/")) {
file.mkdirs();
continue;
}
File parent = file.getParentFile();
if (parent != null) {
parent.mkdirs();
}
// Extract the file
InputStream is = zipFile.getInputStream(zipEntry);
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int length;
while ((length = is.read(bytes)) >= 0) {
fos.write(bytes, 0, length);
}
is.close();
fos.close();
return;
}
}
}
public static String getNewPath(File file) throws IOException {
ZipFile zipFile = new ZipFile(file);
ZipEntry zipEntry = zipFile.getEntry("descriptor.mod");
InputStream inputStream = zipFile.getInputStream(zipEntry);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
return "finalMods/" + readAllLines(reader);
}
private static String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("name")) {
Matcher matcher = Pattern.compile("(?<=name=\").*(?=\")").matcher(line);
if (matcher.find()) content.append(matcher.group());
}
}
return content.toString() + "/";
}}
这是我的代码,在当前状态下我收到错误:
name: common/ | size: 0 | compressed size: 0
name: common/achievements/ | size: 0 | compressed size: 0
name: common/achievements/standard_achievements.txt | size: 5 | compressed size: 5
Exception in thread "main" java.io.FileNotFoundException: finalMods\The Bronze Age: Maryannu\common\achievements\standard_achievements.txt (The filename, directory name, or volume label syntax is incorrect)
at java.base/java.io.FileOutputStream.open0(Native Method)
at java.base/java.io.FileOutputStream.open(FileOutputStream.java:291)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:234)
at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:184)
at com.martin.fParadox.Main.main(Main.java:42)
Process finished with exit code 1
我通过尝试不同的解决方案得到的最接近的方法是将所有文件提取到一个文件夹中,这显然很糟糕,因为很多文件都被覆盖了。
提前谢谢你。
【问题讨论】:
标签: java arrays java-stream zip unzip