下面的代码是我在网上看到的引用中的代码,所以可能有一些相似之处,我正试图实现该代码,以便根据本例中的第一个字段删除整行--它是(aaaa或bbbb)文件,它有一个分隔符“AC.26”,但它不能工作。希望有人能就此给我建议。我需要先分线吗?还是我的方法错了?
player.dat中的数据(例如)
bbbb|aaaaa|cccc
aaaa|bbbbbb|cccc代码如下
public class testcode {
public static void main(String[] args)throws IOException
{
File inputFile = new File("players.dat");
File tempFile = new File ("temp.dat");
BufferedReader read = new BufferedReader(new FileReader(inputFile));
BufferedWriter write = new BufferedWriter(new FileWriter(tempFile));
Scanner UserInput = new Scanner(System.in);
System.out.println("Please Enter Username:");
String UserIn = UserInput.nextLine();
String lineToRemove = UserIn;
String currentLine;
while((currentLine = read.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
write.write(currentLine + System.getProperty("line.separator"));
}
write.close();
read.close();
boolean success = tempFile.renameTo(inputFile);
}
}发布于 2015-04-08 09:35:36
您的代码将从文件中读取的整行代码与用户输入的用户名进行比较,但您在问题中说,实际上您只想将第一部分与第一个管道(|)进行比较。你的代码不会那么做的。
您需要做的是从文件中读取行,获取字符串的一部分到第一个管道符号(拆分字符串),并根据拆分字符串的第一部分与lineToRemove变量的比较跳过行。
为了简化操作,还可以将管道符号添加到用户输入中,然后执行以下操作:
string lineToRemove = UserIn + "|";
...
if (trimmedLine.startsWith(lineToRemove)) continue;这样你就不用再撕开绳子了。
目前我不确定UserInput.nextLine();是否返回换行符。为了在这里安全起见,您可以将上面的内容更改为:
string lineToRemove = UserIn.trim() + "|";https://stackoverflow.com/questions/29510917
复制相似问题