从文件处理文本文件java中删除特定行

时间:2015-01-08 20:49:59

标签: java

    File RaptorsFile = new File("raptors.txt");
    File tempFile = new File("raptorstemp.txt");
    BufferedWriter output = new BufferedWriter (new FileWriter ("raptorstemp.txt"));
    System.out.println("Please enter the following infomation");
    System.out.println("Please enter the Player's Name"); 
    String PlayerName=sc.nextLine();
    System.out.println("Please enter the Player's FG%"); 
    String FieldGoal=sc.nextLine();
    System.out.println("Please  enter the Player's 3P%"); 
    String ThreePointer=sc.nextLine();
    System.out.println("Please enter the Player's FT%"); 
    String FreeThrow=sc.nextLine();
    System.out.println("Please enter the Player's REB"); 
    String Rebounds=sc.nextLine();
    System.out.println("Please enter the Player's AST"); 
    String Assists=sc.nextLine();
    System.out.println("Please enter the Player's Points"); 
    String Points=sc.nextLine();
    String currentLine;
    while((currentLine = Raptors.readLine()) != null) {
        // trim newline when comparing with lineToRemove
        String trimmedLine = currentLine.trim();
        if(trimmedLine.equals(PlayerName+"," +FieldGoal+"," +ThreePointer+"," +FreeThrow+"," +Rebounds+"," +Assists+"," +Points)) continue;
        output.write(currentLine + System.getProperty("line.separator"));
    }

    boolean successful = tempFile.renameTo(RaptorsFile);
    output.close();
    System.out.println("The CarsTemp file will have the new list"); 
    options(Raptors,s);

我遇到了一个问题我只想让用户只输入玩家的名字,例如,如果他输入Kyle Lowry,我希望它删除所有Kyle Lowry的统计数据。以下是文本字段示例。

Lou Williams,41.1,36.3,87.6,60,53,508
Kyle Lowry,44.9,35.1,81.3,160,260,702
Patrick Patterson,48.8,46.0,75.0,177,61,286
Terrence Ross,42.9,38.7,87.9,119,30,411
Jonas Valanciunas,54.2,0.0,79.2,283,16,414

2 个答案:

答案 0 :(得分:0)

您可以使用String.startsWith()方法或匹配正则表达式。

解决方案1 ​​

 while ((currentLine = Raptors.readLine()) != null) {
    if (!currentLine.startsWith(PlayerName + ",")) { // you could use continue as well, but imho it is more readable to put the output.write inside the condition
        output.write(currentLine);
        output.newLine();
    }
 }

此解决方案具有更好的性能,但可能导致误报

解决方案2

 while ((currentLine = Raptors.readLine()) != null) {
    if (!currentLine.matches(PlayerName + ",\\d[\\d.+],\\d[\\d.+],\\d[\\d.+]),\\d+\\d+,\\d+\\s*") { 
        output.write(currentLine);
        output.newLine();
    }
 }

此解决方案完全符合您的标准,但性能更差,看起来更丑。

我认为解决方案1应该运作良好。 请注意,我还没有测试过上面的代码。

PS:坚持使用官方编码约定总是一个好主意,例如变量名应该以小写字符开头等等。

PS2:您可以使用PrintWriter而不是BufferedWriter,它可以为您提供其他方法,例如println,它结合了write(…)newLine()

答案 1 :(得分:0)

所以基本上你循环遍历文件并检查每行文本的开头,看它是否以用户输入开头。您可以使用String方法startsWith()来确定行是否以用户输入开头,如果返回false,则将该行写入临时文件,如果返回true,则跳至输入文件中的下一行。扫描整个输入文件后,将它们全部关闭,将原始文件重命名为备份文件,并将临时文件重命名为原始文件。这不是一个非常复杂的问题。