Original Post
im having an issue working with zip files. a portion of the file is locked, and when the error is thrown it adds the file to the zip anyway. I cannot for the life of me figure out how to either preemptively test for this or remove files from a zip file after the fact. output: hey, i can read! couldnt save file: The process cannot access the file because another process has locked a portion of the file lockedfile.txt -1 (file in zip) (size, sentinel for unknown) i marked with comments where the actual error is thrown. In my real world example another program has control of the lock on the file, so in this test case it is just for demonstrative purposes.
import java.io.*;
import java.nio.channels.*;
import java.util.zip.*;
public class Main {
public static void main(String[] args) {
File file = new File("lockedfile.txt");
FileLock lock;
FileChannel channel;
try {
FileOutputStream out = new FileOutputStream(file);
PrintStream p = new PrintStream(out);
p.print("dilbert doesn't hold back, why should you?");
p.close();
out.close();
channel = (new RandomAccessFile(file, "rw")).getChannel();
lock = channel.tryLock(2,1,false);
if (file.canRead())
System.out.println("hey, i can read!");
else
System.out.println("doh, can't read :(");
byte[] buf = new byte[1024];
ZipOutputStream zout;
// Create the ZIP file
String outFilename = "outfile.zip";
zout = new ZipOutputStream(new FileOutputStream(outFilename));
FileInputStream in;
try {
in = new FileInputStream(file);
// Add ZIP entry to output stream.
zout.putNextEntry(new ZipEntry(file.getName()));
// Transfer bytes from the file to the ZIP file
int len;
//THROWN BELOW
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
//THROWN ABOVE
// Complete the entry
zout.closeEntry();
in.close();
}
catch (IOException e) {
System.out.println("couldnt save file: "+e.getMessage());
}
// Complete the ZIP file
zout.close();
lock.release();
channel.close();
ZipInputStream zin = new ZipInputStream(new FileInputStream(outFilename));
ZipEntry ze;
while ((ze=zin.getNextEntry())!=null) {
System.out.println(ze.getName()+"\t"+ze.getSize());
zin.closeEntry();
}
zin.close();
}
catch (OverlappingFileLockException e) {
System.out.println("file is already locked:"+e.getMessage());
System.exit(1);
}
catch (IOException e) {
System.out.println("zip failed: "+e.getMessage());
System.exit(1);
}
}
}