简体   繁体   English

找到特定的文本行后,如何将新的文本行写入文件?

[英]How can I write a new line of text to a file once a specific line of text has been found?

I'm creating a program that simple creates objects of soccer teams and then stores the names and records of the teams in a text file. 我正在创建一个程序,该程序可以简单地创建足球队的对象,然后将足球队的名称和记录存储在一个文本文件中。

I'm trying to create sections in my file however so I can print out teams that are on the same continent. 但是,我正在尝试在文件中创建部分,以便可以打印出位于同一大陆的团队。

Pretend the next line of text is the beginning of my text file 假装文本的下一行是我的文本文件的开头

North America 北美

End North America 结束北美

Hey guys 大家好

If I want my objects of teams who are in North America only to be written in between those two lines of text how would I do that? 如果我只想将北美团队的对象写在这两行文字之间,我该怎么做?

The results I have gotten so far aren't working correctly, the team name and records are being printed right after "End North America". 到目前为止,我得到的结果无法正常工作,团队名称和记录都在“结束北美”之后打印。

Below is my code thus far. 下面是到目前为止的代码。

import java.util.*;
import java.io.*;

public class Teams {

   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
  Scanner nameInput = new Scanner(System.in);

  System.out.println("Team Creator!");
  System.out.println("-----------------------------");
  System.out.println("Select an option");
  System.out.println("");
  System.out.println("1. Create-A-Team");
  System.out.println("");

  int optionSelection = input.nextInt();
  if(optionSelection==1) {

     System.out.println("Please enter the name of the team you'd like to create");

     String teamName = nameInput.nextLine();
     Team team = new Team();
     team.createTeam(teamName);
          }
       }
    }

class Team {
   String name;
   int wins,loses;
   boolean northAmericanTeam = true;

   public void createTeam(String name) {
      Team newTeam = new Team();
      newTeam.name = name;
      this.wins = 0;
      this.loses = 0;
      System.out.println("You  created " + name + "!");
      System.out.println("Wins: " + wins);
      System.out.println("Loses: " + loses);

  if(northAmericanTeam == true) {
     BufferedReader reader = null;

     try(PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter("teaminfo.txt", true)))) {
        File file = new File("teaminfo.txt");
        reader = new BufferedReader(new FileReader(file));

        String line;
        String nAmerica ="North America";
        while ((line = reader.readLine()) != null) {
           System.out.println(line);

           if(line.equals(nAmerica)) {
              write.println(name+"" + ": Wins[" +wins+"] Loses[" +loses+"]");
              write.close();
           }
        }

     } 
     catch (IOException e) {
        e.printStackTrace();
     } 
     finally {
        try {
           reader.close();
        } 
        catch (IOException e) {
           e.printStackTrace();
            }
         }
      }
   }
}

I don't really know if this is the best solution, but you can maybe do this with pattern. 我真的不知道这是否是最好的解决方案,但是您可以使用模式来做到这一点。

private static final Pattern pAmerica = Pattern.compile("End\\\\sNorth\\\\sAmerica");

And then, in your printer, you can match it and write after : 然后,在您的打印机中,您可以匹配它并在以下内容后写:

while ((line = reader.readLine()) != null) {
           System.out.println(line);
           Matcher mAmerica = pAmerica.matcher(line);
           if(mAmerica.find()) {//Maybe using mAmerica.matches() here can be better
              write.println(name+"" + ": Wins[" +wins+"] Loses[" +loses+"]");
              write.close();
           }
        }

Never forget to compile your pattern in a static way, to ensure minimum perf used, they are hard to compile ^^ 永远不要忘记以静态方式编译模式,以确保使用最低性能,它们很难编译^^

You are assuming that the writer will be placed at the place where the reader has reached, which is not right. 您假设作者将被放置在到达读者的地方,这是不对的。

The moment the reader reaches line 5 for example, the writer will still be attempting to write at the end of the file. 例如,当读取器到达第5行时,写入器仍将尝试在文件末尾进行写入。

You can read the whole file (if it's not that big) into a StringBuilder and then manipulate it, and write i back to the File: 您可以将整个文件(如果不是那么大)读取到StringBuilder中,然后对其进行操作,然后将我写回到File中:

        StringBuilder filecontent = new StringBuilder("Yor File Contents");
        if (filecontent.indexOf("North America") != -1){
            filecontent.insert(filecontent.indexOf("North America\n" + "North America\n".length(), "\n" + name+"" + ": Wins[" +wins+"] Loses[" +loses+"]")
        }

// write filecontent.toString() to the File again

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM