package dev.kske.chess.pgn;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import dev.kske.chess.exception.ChessException;
/**
* Project: Chess
* File: PGNDatabase.java
* Created: 4 Oct 2019
*
* Contains a series of {@link PGNGame} objects that can be stored inside a PGN
* file.
*
* @since Chess v0.5-alpha
* @author Kai S. K. Engelbart
*/
public class PGNDatabase {
private final List games = new ArrayList<>();
/**
* Loads PGN games from a file.
*
* @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 {
try (Scanner sc = new Scanner(pgnFile)) {
while (sc.hasNext())
games.add(PGNGame.parse(sc));
}
}
/**
* Saves PGN games to a file.
*
* @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();
try (PrintWriter pw = new PrintWriter(pgnFile)) {
games.forEach(g -> g.writePGN(pw));
}
}
/**
* @return all games contained inside this database
*/
public List getGames() { return games; }
}