This repository has been archived on 2021-02-18. You can view files and clone it, but cannot push or open issues or pull requests.
chess/src/main/java/dev/kske/chess/pgn/PGNDatabase.java

58 lines
1.5 KiB
Java
Raw Normal View History

package dev.kske.chess.pgn;
2020-01-19 22:12:33 +01:00
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import dev.kske.chess.exception.ChessException;
/**
* Project: <strong>Chess</strong><br>
* File: <strong>PGNDatabase.java</strong><br>
* Created: <strong>4 Oct 2019</strong><br>
* <br>
* Contains a series of {@link PGNGame} objects that can be stored inside a PGN
* file.
2020-01-19 22:12:33 +01:00
*
* @since Chess v0.5-alpha
* @author Kai S. K. Engelbart
*/
public class PGNDatabase {
private final List<PGNGame> games = new ArrayList<>();
/**
* Loads PGN games from a file.
2020-01-19 22:12:33 +01:00
*
* @param pgnFile the file to load the games from
* @throws FileNotFoundException if the specified file is not found
* @throws ChessException if an error occurs while parsing the file
*/
public void load(File pgnFile)
throws FileNotFoundException, ChessException {
2020-01-19 22:12:33 +01:00
try (Scanner sc = new Scanner(pgnFile)) {
while (sc.hasNext())
games.add(PGNGame.parse(sc));
}
}
/**
* Saves PGN games to a file.
2020-01-19 22:12:33 +01:00
*
* @param pgnFile the file to save the games to.
* @throws IOException if the file could not be created
*/
public void save(File pgnFile) throws IOException {
pgnFile.getParentFile().mkdirs();
2020-01-19 22:12:33 +01:00
try (PrintWriter pw = new PrintWriter(pgnFile)) {
games.forEach(g -> g.writePGN(pw));
}
}
2020-01-19 22:12:33 +01:00
/**
* @return all games contained inside this database
*/
public List<PGNGame> getGames() { return games; }
}