如何从Java中的文本文件读取字符串?

时间:2019-03-16 22:49:59

标签: java

我有一个问题,因为我不知道如何从文件中读取一行(我进行了搜索,尝试并没有任何效果)。我需要它,因为我想在以后的项目(游戏中服务器上被阻止的玩家的列表)中使用它。一开始,我将播放器及其被禁止的原因保存到HashMap中。然后,我必须读取该昵称并将其与原因分开,并检查昵称(checkPlayerOnTheBanList方法中的参数(字符串昵称))是否与保存HashMap的文件中的名称一致。然后,如果名称(参数)与文件中的名称匹配,则播放器将无法输入服务器。这是bannedplayers.txt文件的内容:

hacker=Cheating!
player=Swearing!

这是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);
    }

1 个答案:

答案 0 :(得分:2)

一种逐行读取文件并将每行作为元素放入列表的简单方法,希望它可以帮助您根据需要进行修改。

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;
}