Reputation: 101
I'm working on a school project right now, and I amseriously struggling trying to append text to an existing line in my .txt file. What I would like to see is that if a "show name" matches with one in the .txt file the next line which contains [HOST] a username will be added. I've so far created this method:
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;
}
}
At this point I'm quite certain I can't do it because I'm using a reader of some sort, and not a writer, but I wouldn't know how to come around this. I'm quite stuck and has been for a time at this point. I hope some clever minds can tell an quite easy way to come around this. My data set looks like the following:
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]
I really hope some one can help. Thanks in advance!
Upvotes: 0
Views: 189
Reputation: 5331
Try this:
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);
}
}
Before demo.txt file:
After demo.txt file:
Explanation:
demo.txt
file.Line 7
and replace admin HOST
with admin HOST Test
.Note: This is an example that will help you to update code as per your requirement.
Upvotes: 2