tags:

views:

219

answers:

3

I would like to delete a string or a line inside a ".txt" file (for example filen.txt). For example, I have these lines in the file:

1JUAN DELACRUZ
2jUan dela Cruz
3Juan Dela Cruz

Then delete the 2nd line (2jUan dela Cruz), so the ".txt" file will look like:

1JUAN DELACRUZ
3Juan Dela Cruz

How can I do this?

+1  A: 

Get a string with everything from the file in it. Remove what you want. Write the string back to the file, removing all of what was there before. Simple.

Blaise Roth
Ore a get a StrignBuffer/Builder with everything from the file... etc. Still have you considered the case when the file is very big in size ? Wouldn't be inefficient to store such a big quantity of information in memory ?
Andrei Ciobanu
This is the right answer for files that can fit in physical memory. For files that can't, you read the part of the file into a buffer, check if the buffer has any lines to remove and then write it out to a temp file and so on. When done, replace the original file with the temp file using a file copy/move/rename function.
Chinmay Kanchi
-1 Much better to read the file line by line (blockwise) and copy only the lines which don't match the line to delete.
Helper Method
For sufficiently small files, reading the whole thing in one go can be more efficient than going line-by-line.
GWLlosa
This method will be far more efficient for small files, since you only block for IO once each for reading and writing. In the line-by-line method, you block once for each line. The line-by-line method is a bad way to do it even for large files, reading into a large buffer is almost certainly quicker.
Chinmay Kanchi
+2  A: 

1) Scan the file line by line, and write the results in another temporary file.If you encounter the String within a line, remove it, and write only the modified line.

2) Remove the intial file, and rename the temporary file with the name of the initial file.

In order to achieve this, take a look at the File class.

File file = new  File("data.txt");

Then "scan" the file using the Scanner class, as in the following example:

    Scanner scanner = new Scanner(file);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        /* Proccess line */
    }

To write information into a new File, take a look at PrintWriter class.

LATER EDIT:

If you feel confortable with the concept of buffers, you can also use BufferedReader with its read function, in order to process bigger chunks of data, instead of "lines".

Andrei Ciobanu
A: 

If the file is small and it is not a homework, get the apache commons IO and read the file to a String to manipulate it. Download: http://commons.apache.org/io/download_io.cgi How to read: http://www.javadb.com/how-to-read-file-contents-to-string-using-apache-commons-io How to write: http://www.kodejava.org/examples/55.html

Lucass