/
geriot
/
load
Обзор
Документация
Войти
/
geriot
/
load
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
SaveGameManager.java
107 строк
4 KB
geriot
update SaveGameManager.java
08 май 2025, 22:14
08 май 2025, 22:14
792584e
Код
Авторство
О чём код?
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class SaveGameManager { private static final String SAVE_DIR = "/Users/Endless/Desktop/Games/GunRunner/savegames/"; // Путь к папке сохранения public void saveGame(String filePath, GameProgress gameProgress) throws IOException { FileOutputStream fileOut = null; ObjectOutputStream objectOut = null; try { fileOut = new FileOutputStream(filePath); objectOut = new ObjectOutputStream(fileOut); objectOut.writeObject(gameProgress); System.out.println("Игра сохранена в файл: " + filePath); } finally { if (objectOut != null) { try { objectOut.close(); } catch (IOException e) { e.printStackTrace(); } } if (fileOut != null) { try { fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } } } public void zipFiles(String zipFilePath, List<String> filePaths) throws IOException { try (FileOutputStream fos = new FileOutputStream(zipFilePath); ZipOutputStream zipOut = new ZipOutputStream(fos)) { for (String filePath : filePaths) { String fileName = new File(filePath).getName(); try (FileInputStream fis = new FileInputStream(filePath)) { zipOut.putNextEntry(new ZipEntry(fileName)); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zipOut.write(buffer, 0, len); } zipOut.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("Файлы успешно упакованы в архив: " + zipFilePath); } catch (IOException e) { e.printStackTrace(); } } public void deleteOldFiles() { File[] files = new File(SAVE_DIR).listFiles(); for (File file : files) { if (!file.getAbsolutePath().startsWith(zipFilePath(SAVE_DIR))) { System.out.println("Удален файл: " + file.getName()); file.delete(); } } } private String zipFilePath(String saveDir) { return SAVE_DIR + "zip.zip"; } public static void main(String[] args) throws IOException { SaveGameManager manager = new SaveGameManager(); GameProgress progress1 = new GameProgress(100, 5, 3, 250.0); GameProgress progress2 = new GameProgress(75, 8, 4, 180.5); GameProgress progress3 = new GameProgress(90, 12, 5, 300.2); List<String> saveFilePaths = new ArrayList<>(); saveFilePaths.add(SAVE_DIR + "save1.dat"); saveFilePaths.add(SAVE_DIR + "save2.dat"); saveFilePaths.add(SAVE_DIR + "save3.dat"); manager.saveGame(saveFilePaths.get(0), progress1); manager.saveGame(saveFilePaths.get(1), progress2); manager.saveGame(saveFilePaths.get(2), progress3); manager.zipFiles(SAVE_DIR + "zip.zip", saveFilePaths); manager.deleteOldFiles(); } }