Link to home
Start Free TrialLog in
Avatar of izomax
izomax

asked on

Removing a line from file

If I have a file named book.java

and it contains:

book1
book2
book3

now I want to remove book2 so that there's no blank line:

book1
book3

how can I do that? Thanks!
Avatar of Mick Barry
Mick Barry
Flag of Australia image

you'll have to create a new file and write the lines you want to save to the new file and then once done replace the existing file with the new one

Avatar of izomax
izomax

ASKER

Does that mean I have to use RandomAccessFile?
No RAF won't help, it only allow you to overwrite data.
It doesn't let you remove data, or insert data.
No. You'll have to read in all the data, cut out what you don't want, and then output the whole string. Note, if you want to keep your line breaks, use BufferedReader.readLine() and append a "\n" to each line read in. To cut out the data:
int cutPoint = wholeString.indexOf(String stringToCut);
finalString = wholeString.substring(0, cutPoint) + wholeString.substring((cutPoint + 1), wholeString.length());

Then just output finalString to the file (make sure to overwrite).
Errr... Oops. Don't declare the stringToCut in the indexOf...

This:
int cutPoint = wholeString.indexOf(String stringToCut);
should be this:
int cutPoint = wholeString.indexOf(stringToCut);

Oh, and add in after that line:
if (cutPoint == -1){//Error message followed by System.exit(0) or something as a value of -1 will screw up the substring
}

P.S. I assume that all the strings I used were declared earlier. If not, declare them, i.e. String finalString...
use this code. As u've to replace "book2" value with "" empty. and also u've to remove leading new line "\n" char. U'll get ur desired result. Try this code.

    String thisText = "book1\nbook2\nbook3";
    String strRemove = "book2";
    String result = "";
    result = thisText.replaceAll("\n" + strRemove,"");
    System.out.println(thisText);
    System.out.println(result);


bye,
Naeem Shehzad Ghuman
ASKER CERTIFIED SOLUTION
Avatar of CI-Ia0s
CI-Ia0s

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
File f = new File("book.java");
File newf = new File("book.java.new");
BufferedReader in = new BufferedReader(new FileReader(f));
PrintWriter out = new PrintWriter(new FileWriter(newf));
String line = null;
while (null!=(line=in.readLine()))
{
   if (!line.equals("book2"))
   {
      out.println(line);
   }
}
in.close();
out.close();
f.delete();
newf.renameTo(f);
Yea... That'd work too. ;)
So you have your pick of 3 methods, izomax...
Thank you. :)