问题在于这些调用彼此接替:
fileToWrite.mkdirs(); //creates a directory e.g. C:tempfoox fileToWrite.createNewFile(); //attempts to create a file C:tempfoox
创建 *** 作失败,因为您刚刚创建的目录名与要创建的文件相同。
您要执行的 *** 作是:
fileToWrite.getParentFile().mkdirs()
而且,
createNewFile()没有必要拨打电话。
根据您的代码。以下“解压缩”一个zip文件:
import java.io.*;import java.util.zip.ZipFile;import java.util.zip.ZipEntry;import java.util.Enumeration;public class Unzipper { public static void main(String[] args) throws IOException { final File file = new File(args[0]); final ZipFile zipFile = new ZipFile(file); final byte[] buffer = new byte[2048]; final File tmpDir = new File(System.getProperty("java.io.tmpdir"), zipFile.getName()); if(!tmpDir.mkdir() && tmpDir.exists()) { System.err.println("Cannot create: " + tmpDir); System.exit(0); } for(final Enumeration entries = zipFile.entries(); entries.hasMoreElements();) { final ZipEntry zipEntry = (ZipEntry) entries.nextElement(); System.out.println("Unzipping: " + zipEntry.getName()); final InputStream is = zipFile.getInputStream(zipEntry); final File fileToWrite = new File(tmpDir, zipEntry.getName()); final File folder = fileToWrite.getParentFile(); if(!folder.mkdirs() && !folder.exists()) { System.err.println("Cannot create: " + folder); System.exit(0); } if(!zipEntry.isDirectory()) { //No need to use buffered streams since we're doing our own buffering final FileOutputStream fos = new FileOutputStream(fileToWrite); int size; while ((size = is.read(buffer)) != -1) { fos.write(buffer, 0, size); } fos.close(); is.close(); } } zipFile.close(); }}
免责声明:我还没有测试过最基本的内容。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)