我有一个可以在虚拟文件系统(jimfs)上压缩文件的Path,我需要使用ZipFile打开这个压缩文件。
但是ZipFile中没有构造函数来获取Path作为参数,只有File。
但是,我不能从我的Path中创建一个File (path.toFile()),因为我得到了UnsupportedOperationException。如何用ZipFile打开我的压缩文件?或者可能还有其他处理zip文件的方法,而这不是默认的文件系统?
发布于 2016-07-24 16:24:57
ZipFile类仅限于文件系统中的文件。
另一种选择是使用ZipInputStream。从您的InputStream中创建一个Path
Path path = ...
InputStream in = Files.newInputStream(path, openOptions)并使用InputStream创建一个ZipInputStream。这种方式应如预期的那样发挥作用:
ZipInputStream zin = new ZipInputStream(in)因此,推荐的使用方法是:
try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(path))) {
// do something with the ZipInputStream
}注意,使用ZipInputStream will fail because of their ZIP structure解压缩某些ZIP文件。这是ZIP格式的一个技术限制,无法解决。在这种情况下,您必须在文件系统或内存中创建一个临时文件,并使用像ZipFile这样的不同的ZIP类。
发布于 2022-10-04 15:37:19
我刚刚解决了同样的问题(我需要解压缩存储在JimFS文件系统上的zip文件)
罗伯特的回答有问题。ZipFile和ZipInputStream相似,但不相等。ZipInputStream的一个大缺点是,它不会在出现错误或损坏的zip文件时失败。它只是在第一个nextEntry调用上返回null。例如,下面的测试将无错误地通过
@Test
fun testZip() {
val randomBytes = Random.nextBytes(1000)
ZipInputStream(ByteArrayInputStream(randomBytes)).use { zis ->
var zipEntry = zis.nextEntry
while (zipEntry != null) {
println(zipEntry.name)
zipEntry = zis.nextEntry
}
}
}因此,如果是从用户输入或通过不稳定的网络获得的zip文件,则没有机会使用ZipInputStream检查zip。这里唯一的选择是使用Java的FileSystems。如果出现错误zip END header not found,下面的测试将失败。当然,有了正确的zip文件,newFileSystem工作得很好。
@Test
fun testZipFS() {
val randomBytes = Random.nextBytes(1000)
val tmpFile = Files.createTempFile(Path.of("/tmp"), "tmp", ".zip")
Files.write(tmpFile, randomBytes)
val zipFs = FileSystems.newFileSystem(srcZip, null)
val zipRoot = zipFs.rootDirectories.single()
Files.walk(zipRoot).forEach { p ->
println(p.absolutePathString())
}
}https://stackoverflow.com/questions/38552650
复制相似问题