I am having issue with writting a binary file to simple ZIP archive using Java 7's FileSystem
and Files
API.
The problem occur while performing write operation, which throws no exception at all, the file is not written to the ZIP archive, but is available in runtime (Files.exists(backup)
returns true and it's possible to read the file using Files.readAllBytes(backup)
).
When program is closed and relaunched, the file is not available anymore.
Snippet
This method should create backup of any path, no matter who is the FileSystem provider, 'fails' just on paths inside ZIP archives.
/**
* Creates backup of path provided by 'file' parameter.
*
* @param file input file requiring backup creation
* @return backup file
* @throws java.io.IOException thrown in case of unsuccessful backup attempt
*/
public static Path createBackup(Path file) throws IOException {
FileSystem fileSystem = file.getFileSystem();
Path backup = fileSystem.getPath(file.toString() + ".BAK");
return Files.write(backup, Files.readAllBytes(file));
}
public static void main(String... args) {
try {
Path f = FileSystems.newFileSystem(Paths.get("a.zip"), null).getPath("file.bin");
Path backup = createBackup(f);
System.out.println(Files.exists(backup)); // prints "true"
System.out.println(new String(Files.readAllBytes(backup))); // prints its bytes
System.out.println(backup.toString()); // prints "file.bin.BAK"
} catch (IOException ex) {
System.err.println(ex);
}
}
But the file does not physically exists in the ZIP.
EDIT: I've managed to make it work, but there is a problem. Code below closes the file system, but writes properly. There is need to "refresh"/"reopen" filesystem somehow.
public static Path createBackup(Path file) throws IOException {
try(FileSystem fileSystem = file.getFileSystem()) {
Path backup = fileSystem.getPath(file.toString() + ".BAK");
return Files.write(backup, Files.readAllBytes(file));
}
}
When original method is keept and file system is closed manually after everything is done, it removes the zip file and keeps something like zipfstmp***.tmp
and throws:
java.nio.file.FileAlreadyExistsException: zipfstmp2666831581340533856.tmp -> a.zip
When the tmp file is renamed to "a.zip", its a valid modified archive.