[英]Append text to existing line in a file
我現在正在做一個學校項目,我正在努力嘗試將 append 文本添加到 my.txt 文件中的現有行。 我想看到的是,如果“顯示名稱”與 .txt 文件中的一個匹配,則將添加包含 [HOST] 的下一行用戶名。 到目前為止,我已經創建了這個方法:
public void joinAShow(String username, String showName) throws IOException{
keepGoing = true;
keepGoing2 = true;
while((line = bufferedReader2.readLine()) != null && keepGoing){
if(line.equals(showTitle)){
while((line = bufferedReader2.readLine()) != null && keepGoing2){
if(line.contains("[HOST]")){
line += ", " + username;
}
}
}
keepGoing = false;
keepGoing2 = false;
}
}
在這一點上,我很確定我做不到,因為我使用的是某種閱讀器,而不是作家,但我不知道如何解決這個問題。 我被困住了,在這一點上已經有一段時間了。 我希望一些聰明的頭腦可以告訴一個非常簡單的方法來解決這個問題。 我的數據集如下所示:
Stream1
Review
Stream
2020-10-10 10:00
90
0.0
admin[HOST]
Stream2
Review
Stream
2020-10-10 10:00
90
0.0
admin[HOST]
Stream3
Review
Stream
2020-10-10 10:00
90
0.0
admin[HOST]
我真的希望有人可以提供幫助。 提前致謝!
嘗試這個:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Demo {
public static void main(String[] args) throws IOException {
// Update line number 7 and append Test to it
updateLine(7, "Test");
}
public static void updateLine(int lineNumber, String data) throws IOException {
// Path of file
Path path = Paths.get("etc/demo.txt");
// Read all lines
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// Update line 7 - Replace admin HOST with admin HOST Test
lines.set(lineNumber - 1, lines.get(lineNumber - 1) + " " + data);
// Write back to the file
Files.write(path, lines, StandardCharsets.UTF_8);
}
}
在 demo.txt 文件之前:
在 demo.txt 文件之后:
解釋:
demo.txt
文件中逐行讀取數據。Line 7
並將admin HOST
替換為admin HOST Test
。注意:這是一個示例,可幫助您根據需要更新代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.