I want to create a program that will replace some of the text within a text file, however when I attempt to do so it deletes the rest of the file so I'm left with just the replaced line.
For example if i want to change the fourth record from e to d it deletes items within the file.
Text File before
1 a
2 b
3 c
4 e
Text File after
4 d
Can anyone help??
//package org.kodejava.example.io; import java.io.*; import java.util.*; public class LineNumberReaderExample { public static void main(String[] args) throws Exception { File file = null; FileReader fr = null; LineNumberReader lnr = null; try { Scanner input=new Scanner(System.in); System.out.print("Enter record to edit "); String word=input.next(); file = new File("file.txt"); fr = new FileReader(file); lnr = new LineNumberReader(fr); String line = ""; while ((line = lnr.readLine()) != null) { if(line.startsWith(word)){ System.out.println("Line Number " + lnr.getLineNumber() + ": " + line); String[] st = line.split(" "); String date = st[0]; String event = st[1]; System.out.print("Replace With: "); String newtext=input.next(); FileWriter writer = new FileWriter("file.txt"); writer.write(line.replace(event, newtext)); writer.close(); } } } finally { if (fr != null) { fr.close(); } if (lnr != null) { lnr.close(); } } } }
Once I get this code working I can then save dates and events to the text file.