Anexando a depuração do arquivo zip
Então, eu estava interessado em anexar arquivos a um arquivo zip e me deparei com alguns usuários que fizeram essa pergunta antes e outro usuário deu esse trecho de código como uma solução para esse problema:
public static void updateZip(File source, File[] files, String path){
try{
File tmpZip = File.createTempFile(source.getName(), null);
tmpZip.delete();
if(!source.renameTo(tmpZip)){
throw new Exception("Could not make temp file (" + source.getName() + ")");
}
byte[] buffer = new byte[4096];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(source));
for(int i = 0; i < files.length; i++){
System.out.println(files[i].getName()+"being read");
InputStream in = new FileInputStream(files[i]);
out.putNextEntry(new ZipEntry(path + files[i].getName()));
for(int read = in.read(buffer); read > -1; read = in.read(buffer)){
out.write(buffer, 0, read);
}
out.closeEntry();
in.close();
}
for(ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry()){
if(!zipEntryMatch(ze.getName(), files, path)){
out.putNextEntry(ze);
for(int read = zin.read(buffer); read > -1; read = zin.read(buffer)){
out.write(buffer, 0, read);
}
out.closeEntry();
}
}
out.close();
tmpZip.delete();
}catch(Exception e){
e.printStackTrace();
}
}
private static boolean zipEntryMatch(String zeName, File[] files, String path){
for(int i = 0; i < files.length; i++){
if((path + files[i].getName()).equals(zeName)){
return true;
}
}
return false;
}
Eu criei um mini programa para testar este método e este é o método que faz todo o trabalho:
private static void appendArchive() {
String filename = "foo";
File[] filelist = new File[10];
int i = 0;
String temp = "";
while (!filename.trim().equals("")) {
System.out
.println("Enter file names to add, then enter an empty line");
filename = getInput();
filelist[i] = new File(filename, filename);
System.out.println("Adding " + filelist[i].getName());
}
System.out
.println("What is the name of the zip archive you want to append");
File zipSource = new File(getInput() + ".zip", "testZip.zip");
try {
Archiver.updateZip(zipSource, filelist, "");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sempre que tento executar este programa, recebo este erro, seguido pelo seguinte:
java.lang.Exception: Could not make temp file (testZip.zip)
at Archiver.updateZip(Archiver.java:68)
at main.appendArchive(main.java:62)
at main.main(main.java:29)
Eu suspeitava que o arquivo zip que eu estava passando era considerado aberto por alguma razão, e então o método de renomeação não estava funcionando no Windows, então eu tentei usar o construtor para o arquivo zip que você vê agora. O que exatamente estou fazendo errado aqui. Minha entrada de teste é 2 para o arquivo e 2 (que é anexada ao 2.zip). Não deve haver problemas relacionados ao diretório, pois os arquivos são gerados pelo programa.