简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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