I am having a a bit of trouble trying to replace a line in a text file with the user input. Whenever I try to replace the line all other lines in the text file gets deleted. Can anyone assist me with this issue?
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out
.println("I see you are trying to update some information... Shall I go ahead?");
String go = input.readLine();
if (go.equals("yes")) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
break;
}
if (go.equals("no")) {
System.out.println(line);
System.out.println("Have a good day!");
break;
}
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
And here is my main
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
String[] keywords = { "day", "month" };
Scanner in = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
String input = null;
System.out.println("Welcome");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
for (int i = 0; i < keywords.length; i++) {
if (input.contains(keywords[i])) {
removedata(keywords[i]);
}
}
}
And my textfile contains " the day is tuesday" and "the month is march". Aassuming the user enters "the day is wednesday" I want to replace the old line with the new line. Any suggestions?