public class MainClass
public static void main(String args)
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
File f = new File("Test.txt");
RandomAccessFile raf = new RandomAccessFile(f,"rw");
String s = raf.readLine();
s = raf.readLine();
String newStr = br.readLine();
int l = s.length();
System.out.println("length: " + l);
for(int i=1; i<=l; i++)
This is just a practice program. It is meant to replace the second line with a new record. But instead of backspacing "\b" it overwrites the third line and when it writes "newStr" it also overwrites.
This is totally not what I'm trying to get. I want to remove the second line by backspacing it and then insert a new string in its place without touching the third line.
How do I do this?
If you want to put a different character at the start of line 2 you need to set the file pointer to that position (using seek), and then you can start overwriting.
[ February 25, 2008: Message edited by: Ulf Dittmer ]
Generally if you want to do this sort of thing, you'd be better off keeping the file in memory as, say, an ArrayList if String objects, each one representing one line. Or perhaps a LinkedList, or perhaps containing StringBuilder objects instead of Strings. Make your changes to the objects in memory, and then, when you're done with all the changes, write a new file, probably using PrintWriter. (Or if you're on a JDK prior to JDK 5, using a PrintWriter wrapped in a BufferefWriter wrapped in a FileWriter - blech.)
Incidentally, having an empty catch block there is a very bad idea, even in a practice program. If anything at all goes wrong, you will hide the error and waste time because you can't see what happened. Putting a simple e.printStackTrace() in the catch block can save you a lot of time later.