Sign in with
Sign up | Sign in
Your question

How to replace a line in a textfile using java

Tags:
  • Cloud Computing
  • Java
  • Business Computing
Last response: in Business Computing
Share
March 6, 2013 5:42:34 AM

hi gud day everyone;

i want to replace a line in a text file ...and here is my code


import java.io.*;

public class exampletextfile
{
public static void main(String args[])throws IOException
{
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
File file = new File("StudGrades.itp");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line="";

System.out.print("Find: ");
String del=input.readLine();

while((line = reader.readLine()) != null)
if(line.contains(del))
{
System.out.print(line );
}



System.out.print("\nReplace with:" );
String replacement=input.readLine();


if(line.contains(del))
{
line= replacement.replace(del,line);
}

FileWriter writer = new FileWriter("StudGrades.itp");
writer.write(line);
reader.close();
writer.close();

}
}

im done with the displaying of the line my only problem is the replacement part
here's the info i have in the text file

1 090-2012-0032,98.0,90.0,95.0,96.0,95.0
2 090-2012-0033,98.0,90.0,95.0,96.0,95.0

i just want to replace a single line then i need to input the new grades from prelim to finals and compute for the subject grade.

here's my code for that:
(in what part of the program can i insert these codes.?)
System.out.println("Enter Student number:");
String sn=input.readLine();
System.out.println("Enter prelim grade:");
p=Integer.parseInt(input.readLine());
System.out.println("Enter midterm grade:");
m=Integer.parseInt(input.readLine());
System.out.println("Enter prefinal grade:");
pf=Integer.parseInt(input.readLine());
System.out.println("Enter final grade:");
f=Integer.parseInt(input.readLine());


sg=(p*.2)+(m*.2)+(pf*.2)+(f*.4);

in my case all lines are being deleted whenever i input the infos.


i hope someone can help me with my program....thanks

More about : replace line textfile java

March 6, 2013 6:14:13 AM

A good way to do this would be to create a temporary output file, let's say temp.txt. You copy everything before that the replacement line to temp.txt. You then write the new line to temp.txt. Afterwards you write everything after the replacement line to temp.txt. temp.txt should now be the exact same as the old file except with the line replaced. Delete the old file and rename temp.txt to StudGrades.itp.

The advantage of this method is that if something goes wrong, or you kill the process while it's running, then you won't corrupt your old file. Replacing text in a file in-place can be tricky since you need to account for the line increasing or decreasing in size, and if something goes wrong, your file could be pooped.

If you have any more programming problems, I would advise asking them on stack overflow instead.
!