|
| 1 | +package logic; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.IOException; |
| 5 | +import java.nio.file.Files; |
| 6 | +import java.nio.file.Path; |
| 7 | +import java.util.logging.Level; |
| 8 | +import java.util.logging.Logger; |
| 9 | + |
| 10 | +/** |
| 11 | + * Thrown when an error occurs during level file operations. |
| 12 | + */ |
| 13 | +class LevelFileException extends RuntimeException { |
| 14 | + public LevelFileException(String message, Throwable cause) { |
| 15 | + super(message, cause); |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Simple utility class for handling level file paths. |
| 21 | + */ |
| 22 | +public class LevelFile { |
| 23 | + private static final Logger LOGGER = Logger.getLogger(LevelFile.class.getName()); |
| 24 | + private static final String LEVELS_DIR = "levels"; |
| 25 | + /** |
| 26 | + * Creates a new LevelFile instance for the given level name. |
| 27 | + * @param levelName the name of the level (without .txt extension) |
| 28 | + * @return a new LevelFile instance |
| 29 | + */ |
| 30 | + public static LevelFile of(String levelName) { |
| 31 | + return new LevelFile(levelName); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Deletes the level file if it exists. |
| 36 | + * @return true if the file was successfully deleted, false otherwise |
| 37 | + */ |
| 38 | + public boolean delete() { |
| 39 | + try { |
| 40 | + return Files.deleteIfExists(getFilePath()); |
| 41 | + } catch (IOException e) { |
| 42 | + String errorMsg = "Error while deleting level file: %s".formatted(levelName); |
| 43 | + LOGGER.log(Level.SEVERE, errorMsg, e); |
| 44 | + return false; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + private final String levelName; |
| 49 | + |
| 50 | + private LevelFile(String levelName) { |
| 51 | + this.levelName = levelName + ".txt"; |
| 52 | + } |
| 53 | + |
| 54 | + private Path getFilePath() throws IOException { |
| 55 | + return getLevelsDirectory().resolve(levelName); |
| 56 | + } |
| 57 | + |
| 58 | + private Path getLevelsDirectory() throws IOException { |
| 59 | + return new File(".").getCanonicalFile().toPath().resolve(LEVELS_DIR); |
| 60 | + } |
| 61 | +} |
0 commit comments