java - How to check if txt file contains a String, if so don't duplicate it

问题描述:

So right now I'm making a mod in Minecraft where it takes everyones username from a server and adds it to a txt file, it works but the the problem is I don't want to duplicate the names when I use the command again. Nothing has worked so far. How would I check if the txt already contains the username, don't add it again? Thank you. Again, I need it to before writing another name to the list, check the txt file if it already contains the name, if so don't add it.

for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {

for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {

GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);

String playerName = StringUtils.stripControlCodes(playerInfo.name);

String lines;

try {

if ((lines = bufferedReader.readLine()) != null) {

if (!lines.contains(playerName)) {

bufferedWriter.write(playerName);

bufferedWriter.newLine();

bufferedWriter.flush();

}

}

} catch (IOException e) {

e.printStackTrace();

}

}

int linenumber = 0;

try {

while (lineNumberReader.readLine() != null) {

linenumber++;

}

} catch (IOException e) {

e.printStackTrace();

}

网友答案:

The logic of your second piece of code is wrong. If you write out the pseudo-code of it, it's easy to see why:

Open a File Reader at the start of the file
For every Player on the server
Save the player name
Read the next line of the file
If we have not reached the end of the file
If the player name is not on this line of the file
Write the name of the player to the file

You need to read the entire file outside of the loop, and then check if the player exists anywhere in the file, not just if it happens to be on the line which is the same position as the player on the server.

The easiest way to do this is to keep the players in a list while you're processing, and read/write them to file, like this: