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

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: <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.
*
* @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.
*
* @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<PGNGame> getGames() { return games; }
}