0

I have a problem because I don't know how to read a line from a file (I searched, I tried and nothing worked). I need it because I want to use it in my future project (list of blocked players on the server in my game). At the beginning, I save the player and the reason for the ban to the HashMap. Then I have to read this nickname and separate it from the reason and check if the nickname (parameter in the checkPlayerOnTheBanList method (String nick)) agrees with the name in the file to which I saved HashMap. Then if the name (parameter) matches with the name in the file then the player won't be able to enter to the server. Here is the content of the bannedplayers.txt file:

hacker=Cheating!
player=Swearing!

Here is the part of Server.java:

public HashMap<String, String> bannedPlayersWr = new HashMap<String, String>();

public void start(String nick) {
    banPlayer("player", "Swearing!");
    banPlayer("hacker", "Cheating!");
    boolean player = checkPlayerOnBanMap(nick);

    if (player) {
        System.out.println("You are banned! Your nick: " + nick);
        System.out.println("Reason: " + bannedPlayersWr.get(nick));

        try {
            FileWriter fstream;
            BufferedWriter out;

            fstream = new FileWriter("C:/Users/User/Desktop/bannedplayers.txt");
            out = new BufferedWriter(fstream);

            Iterator<Entry<String, String>> it = bannedPlayersWr.entrySet().iterator();

            while (it.hasNext()) {
                Entry<String, String> pairs = it.next();
                out.write(pairs.toString() + "\n");
            }
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Welcome to the server! Your nick: " + nick);
        }
    }

    private void banPlayer(String nick, String reason) {
        bannedPlayersWr.put(nick, reason);
    }
MeoNek
  • 1

1 Answers1

2

A simple way to read a file line by line and put each line as an element in a list, hope it helps you to modify it to your need.

private List<String> readFile(String filename)
  throws Exception
{
  String line = null;
  List<String> records = new ArrayList<String>();

  // wrap a BufferedReader around FileReader
  BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));

  // use the readLine method of the BufferedReader to read one line at a time.
  // the readLine method returns null when there is nothing else to read.
  while ((line = bufferedReader.readLine()) != null)
  {
    records.add(line);
  }

  // close the BufferedReader when we're done
  bufferedReader.close();
  return records;
}