Ниже показан мой текущий код. Чтобы проиллюстрировать, что я пытаюсь сделать, я сначала вызываю метод getPath, который просто получает путь к текущему каталогу. Затем я вызываю createZipFile для создания сжатого файла, а затем создаю массив файлов из текущего каталога. Наконец, я перебираю этот массив, вызывая zipFile для каждого файла. Я использую try-with-resources для каждого потока в этом методе. Стоит отметить, что изначально созданный zip-файл не был недействительным, хотя и состоял только из последнего файла в массиве. Я добавил «true» в FileOutputStream (для добавления), что привело меня к моей текущей проблеме.
Код: Выделить всё
public static Path currentDirectory; // directory to zip
public static File[] files; // files in current folder
public static File newZip; // the created zip file
// will retrieve all files in currentDirectory, and zip them
public static void findFiles() {
getPath();
createZipFile();
File thisFolder = new File(String.valueOf(currentDirectory)); // current folder
files = thisFolder.listFiles(); // all files in current folder
for (File f : files) {
zipFile(f.getName());
}
}
public static Boolean createZipFile() {
newZip = new File("test.zip");
try {
if (!newZip.exists()) {
if (newZip.createNewFile()) {
System.out.println("Zip file created!");
return true;
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return false;
}
public static void zipFile(String fileName) {
try (FileOutputStream fos = new FileOutputStream(newZip, true)) {
File inputFile = new File(fileName);
try (FileInputStream fis = new FileInputStream(inputFile)) {
try (ZipOutputStream zos = new ZipOutputStream(fos)) {
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
System.out.println("Zipping file "+fileName+"!");
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
} catch (Exception e) {
System.out.println("ZOS Error: "+e.getMessage());
}
} catch (Exception e) {
System.out.println("FIS Error: "+e.getMessage());
}
} catch (Exception e) {
System.out.println("FOS Error: "+e.getMessage());
}
}
// sets currentDirectory, i.e. folder to zip
public static void getPath() {
Path currentPath = Paths.get("");
String pathString = String.valueOf(currentPath.toAbsolutePath());
currentDirectory = Paths.get(pathString);
}
Я также поискал решения в Интернете и увидел, что обычное решение состоит в том, чтобы убедиться, что потоки были закрыты. Однако, поскольку я использую try-with-resources, я совершенно уверен, что это ко мне не относится.
Подробнее здесь: https://stackoverflow.com/questions/791 ... am-invalid
Мобильная версия