Suppose I've a couple of objects' values stored on a text file. In the beginning, there will be some values which will have the same value, for instance, all students by default will have 0 age. Now if I want to make an edit in the age of one student using the conventional file handling approach, I'll end up making changes to all other students who have 0 age, while writing my data onto the temporary file. Thus, I was hoping that if there is a better way to make changes to a file using file handling in java. Just to give an example of the issue at hand consider the following text file
Edsger
Dijkstra
123
72 years
Ruth
Dijkstra
12345
29 years
The line indicates a space between the age and the name. Now, my task is to construct a program where a user can change any detail, such as the First Name, surname, roll_number or the age. As you can see from the example given above, two people can share some data that is common. In this case, it is the surname. However, the roll number (123,12345) will always be unique. The problem comes when you have to change similar data. Suppose the user wants to edit the surname. Then by I would create a temporary file which would hold this data and later I would read this data with some conditions to it. So the code might look like this:
Note: This data is stored at a known location "abc.txt"
.
BufferedReader br=new BufferedReader(new FileReader("abc.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("Temp.txt"));
String a=br.readLine();
while(a!=null)
{ bw.write(a);
bw.newLine();
a=br.readLine();
}
br.close();
bw.close();
BufferedReader br1=new BufferedReader(new FileReader("Temp.txt"));
BufferedWriter bw1=new BufferedWriter(new FileWriter("temp.txt"));
String b=br1.readLine();
while(b!=null)
{
if(b.equals(requested_surname))
bw1.write(w);//w is the String that holds the altered surname as desired by the User, for the sake of an example say it is Euler
else
bw1.write(b);
bw1.newLine();
b=br1.readLine();
}
bw1.close();
br1.close();
f.delete();
As a result the Original text file "abc.txt"
will show something like this:-
Edsger
Euler
123
72 years
Ruth
Euler
12345
29 years
Now this will be a bungling problem as I intend to change only Ruth's surname! I know that this is slightly different from what I initially asked, but I think that if I could target the line below "Ruth", I can make the desired changes.
Please Help...