gpt4 book ai didi

java - java中的zip创建错误

转载 作者:搜寻专家 更新时间:2023-11-01 03:36:21 24 4
gpt4 key购买 nike

我正在使用 ZipOutputStream、FileOutputStream 和 FileInputStream。

首先,我创建了一个包含一个文件的文件夹。它创建成功。然后我尝试创建 zip 文件。动态地,它第一次正确创建文件,但第二次、第三次在打开文件时出错。

Error: zip [path/././file.zip] Cannot open The process cannot access the file because it is being used by another process. I created following code in java,

我的代码:

 demopath+="/myzip"+po.getPoid();
createDir(demopath);
createFileForFamilies("My content", demopath+"/file");
this.zipDirectory(new File(demopath), demopath+".zip");

我的文件创建者函数:

public String createFileForFamilies(String content, String path) {
FileOutputStream fop = null;
File file;
try {

file = new File(path);
fop = new FileOutputStream(file);

// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}

// get the content in bytes
byte[] contentInBytes = content.getBytes();

fop.write(contentInBytes);
fop.flush();
fop.close();

return ("Done");

} catch (IOException e) {
System.err.println(e);
return ("Done");
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
System.err.println(e);
return ("Abort");

}
}
}

我的 Zip 创建函数:

public void zipDirectory(File dir, String zipDirName) {
try {
populateFilesList(dir);
//now zip files one by one
//create ZipOutputStream to write to the zip file
FileOutputStream fos = new FileOutputStream(zipDirName);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String filePath : filesListInDir) {
System.out.println("Zipping " + filePath);
//for ZipEntry we need to keep only relative file path, so we used substring on absolute path
ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length() + 1, filePath.length()));
zos.putNextEntry(ze);
//read the file and write to ZipOutputStream
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();

}
zos.close();
fos.close();


} catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

谢谢鲍里斯...

这是一个解决方案:

 Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/"+zipPath+".zip");

try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
java.nio.file.Path externalTxtFile;
java.nio.file.Path pathInZipfile ;

externalTxtFile = Paths.get(gamesPath);
pathInZipfile = zipfs.getPath("/file.txt");
Files.copy(externalTxtFile, pathInZipfile,
StandardCopyOption.REPLACE_EXISTING);
}

关于java - java中的zip创建错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30438329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com