[英]How can I write a new line of text to a file once a specific line of text has been found?
我正在創建一個程序,該程序可以簡單地創建足球隊的對象,然后將足球隊的名稱和記錄存儲在一個文本文件中。
但是,我正在嘗試在文件中創建部分,以便可以打印出位於同一大陸的團隊。
假裝文本的下一行是我的文本文件的開頭
北美
結束北美
大家好
如果我只想將北美團隊的對象寫在這兩行文字之間,我該怎么做?
到目前為止,我得到的結果無法正常工作,團隊名稱和記錄都在“結束北美”之后打印。
下面是到目前為止的代碼。
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();
}
}
}
}
}
我真的不知道這是否是最好的解決方案,但是您可以使用模式來做到這一點。
private static final Pattern pAmerica = Pattern.compile("End\\\\sNorth\\\\sAmerica");
然后,在您的打印機中,您可以匹配它並在以下內容后寫:
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();
}
}
永遠不要忘記以靜態方式編譯模式,以確保使用最低性能,它們很難編譯^^
您假設作者將被放置在到達讀者的地方,這是不對的。
例如,當讀取器到達第5行時,寫入器仍將嘗試在文件末尾進行寫入。
您可以將整個文件(如果不是那么大)讀取到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.