JAVA = Replace a line in a text file
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??
Code :
//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.
Re: JAVA = Replace a line in a text file
To change the middle of a file, you need to copy everything before the changed area to an output file, then write the changed part and then copy everything after the changed area to the output file.
There is a case when the new data EXACTLY byte for byte replaces the old data where you could use the RandomAccessFile class to write the new data over the top of the old data.
Re: JAVA = Replace a line in a text file
Can you post the contents of the input file and the contents of the file that is written out?
For testing you should use different files for input and output.
Re: JAVA = Replace a line in a text file
Sorry I've changed my method of saving now. Ignore this thread
Re: JAVA = Replace a line in a text file
Could you please upload your final codes? Thanks :)
Re: JAVA = Replace a line in a text file
Probably not, since this topic is several months old. Start a new topic if you need help to solve a similar problem.