/
Ersh
/
HomeworkCore2.GameInstaller
Обзор
Документация
Войти
/
Ersh
/
HomeworkCore2.GameInstaller
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
GameInstaller/src/SaveMain.java
87 строк
3 KB
Ersh
upload files
08 дек 2025, 14:35
08 дек 2025, 14:35
6d23ece
Код
Авторство
О чём код?
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class SaveMain { public static void main(String[] args) { String savegamesDir = "C:/Users/KirillErshov/IdeaProjects/Games/savegames"; GameProgress save1 = new GameProgress(100, 5, 10, 123.5); GameProgress save2 = new GameProgress(80, 3, 15, 300.0); GameProgress save3 = new GameProgress(50, 1, 5, 45.2); String file1 = savegamesDir + "/save1.dat"; String file2 = savegamesDir + "/save2.dat"; String file3 = savegamesDir + "/save3.dat"; saveGame(file1, save1); saveGame(file2, save2); saveGame(file3, save3); List<String> filesToZip = List.of(file1, file2, file3); String zipPath = savegamesDir + "/saves.zip"; zipFiles(zipPath, filesToZip); for (String filePath : filesToZip) { File file = new File(filePath); if (file.delete()) { System.out.println("Удалён файл: " + filePath); } else { System.err.println("Не удалось удалить файл: " + filePath); } } System.out.println("Сохранения успешно заархивированы и исходные файлы удалены."); } public static void saveGame(String filePath, GameProgress progress) { try (FileOutputStream fos = new FileOutputStream(filePath); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(progress); System.out.println("Сохранение записано: " + filePath); } catch (IOException e) { System.err.println("Ошибка при сохранении: " + e.getMessage()); } } public static void zipFiles(String zipPath, List<String> filePaths) { try (FileOutputStream fos = new FileOutputStream(zipPath); ZipOutputStream zos = new ZipOutputStream(fos)) { for (String filePath : filePaths) { File file = new File(filePath); if (!file.exists()) { System.err.println("Файл не найден: " + filePath); continue; } String entryName = file.getName(); ZipEntry zipEntry = new ZipEntry(entryName); zos.putNextEntry(zipEntry); try (FileInputStream fis = new FileInputStream(file)) { byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } } zos.closeEntry(); System.out.println("Добавлен в архив: " + entryName); } } catch (IOException e) { System.err.println("Ошибка при архивации: " + e.getMessage()); } } }