Arraylist <>为空,尽管已在构造函数中初始化

时间:2018-07-18 08:52:30

标签: java json arraylist constructor

我在Java中制作了一个小型(151.188164, -33.654437),并且您应该知道它应该是静态的,并且我需要一个小型数据库,因此决定制作一个内存数据库。问题在于数据库类应该是静态的,以便在服务器内部使用它。

所以我改变了主意,尝试将数据存储在json文件中,每当需要数据时,只需从文件中读取即可。为了简短起见,我需要使用arraylist。它在构造函数中初始化。但是使用它时,它为null:|

这是我的代码:

httpserver

任何帮助或建议将不胜感激。谢谢你们

2 个答案:

答案 0 :(得分:0)

可能只是找不到文件。如果将文件放在源根目录中(例如,标准maven项目中的src/main/resources/),则可以使用

从类路径中读取文件
InputStream in = this.getClass().getClassLoader().getResourceAsStream(PLAYERS_FILE);

我会稍微重构代码,例如:

import java.io.*;
import java.util.*;

public class DbContext {

    // use constants, not String literals
    public static final String PLAYERS_FILE = "players.json";

    // use interfaces where possible rather than concrete implementation type
    private List<Player> players;

    public DbContext() {
        // the initialization was always overwritten
        // just assign directly from the method
        this.players = readPlayers();
    }

    public Optional<Player> getPlayerByIds(long id, long boardId) {
        for (Player p : players) {
            if (p.getBoardId() == boardId && p.getId() == id) {
                // no need to write players here since there is no change
                // writePlayers();
                return Optional.of(p);
            }
        }
        // do not return null from a method, use Optional instead
        return Optional.empty();
    }

    public void updatePlayer(Player player) {

        // this will not work. player will not get added in the list if you reassign a local variable
        // for (Player p : players) {
        //    if (p.getId() == player.getId()) {
        //        p = player;

        Optional<Integer> playerIndex = findPlayer(player);
        if (playerIndex.isPresent()) {
            players.set(playerIndex.get(), player);
        } else {
            // if the player is not found you can either add the player
            addPlayer(player);
            // ... or throw an exception
            // throw new DbContextException(String.format("Could not find player to update: %s", player));
            // returning a boolean to indicate failure is sort of evil
        }
    }

    private Optional<Integer> findPlayer(Player player) {
        for (int i = 0; i < players.size(); i++) {
            if (players.get(i).getId() == player.getId()) {
                return Optional.of(i);
            }
        }
        return Optional.empty();
    }

    public void addPlayer(Player player) {
        // if you want players to be unique in the list, you should do some checking here
        players.add(player);
        writePlayers();
    }

    // never used
//    private boolean playerExists(Player player) {
//        for (Player p : players) {
//            if (p.getId() == player.getId()) {
//                return true;
//            }
//        }
//        return false;
//    }

    // refactored methods below so each method does only one thing, or at least operates at a single level of abstraction

    private List<Player> readPlayers() {
        try (BufferedReader br = new BufferedReader(new FileReader(PLAYERS_FILE))) {
            return readPlayers(br);
        } catch (IOException e) {
            // DbContextException extends RuntimeException
            throw new DbContextException(String.format("Could not read players from %s", PLAYERS_FILE), e);
        }
    }

    private List<Player> readPlayers(BufferedReader br) throws IOException {
        List<Player> players;
        if (br.read() > 0) {
            players = readPlayersAvailable(br);
        } else {
            players = new ArrayList<>();
        }
        return players;
    }

    private List<Player> readPlayersAvailable(BufferedReader br) {
        List<Player> players;
        Gson gson = new Gson();
        // this looks hacky. in Gson 2.8.0 you can use TypeToken.getParameterized(ArrayList.class, Player.class).getType()
        Type type = new TypeToken<ArrayList<Player>>() {
        }.getType();
        players = gson.fromJson(br, type);
        return players;
    }

    private void writePlayers() {
        try (FileWriter writer = new FileWriter(PLAYERS_FILE)) {
            writePlayers(writer);
        } catch (IOException e) {
            throw new DbContextException(String.format("Could not write players to %s", PLAYERS_FILE), e);
        }
    }

    private void writePlayers(FileWriter writer) throws IOException {
        Gson gson = new Gson();
        gson.toJson(players, writer);
        writer.flush();
    }
}

在我看来,readPlayersAvailable中的代码无法正常工作。我建议您看一下Gson(也许会切换到最新版本),并检查fileReader是否确实找到了您的文件。

答案 1 :(得分:0)

多亏了“ Adriaan Koster”和“ Sumesh TG”,我终于找到了解决方案。看来gson无法将json转换为我的课程。所以我决定手动对其进行解析。

String currentLine;
List<Player> playerList = new ArrayList<>();
while ((currentLine = br.readLine()) != null) {
    Player p = new Gson().fromJson(currentLine, Player.class);
    System.out.println(p.toString());
    playerList.add(p);
}