gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:36:28 25 4
gpt4 key购买 nike

我有一个问题,因为我不知道如何从文件中读取一行(我搜索,我尝试,但没有任何效果)。我需要它,因为我想在我 future 的项目中使用它(我的游戏服务器上被阻止的玩家列表)。一开始,我将玩家和封禁的原因保存到HashMap中。然后我必须读取这个昵称并将其与原因分开,并检查昵称(checkPlayerOnTheBanList方法中的参数(String nick))是否与我保存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);
}

最佳答案

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

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

关于java - Java中如何从文本文件中读取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55202275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com