Search code examples
javaandroidfileoutputstreamandroid-file

how can I delete line from txt?


I mean , I want to delete line from my text on android. How can I delete? I do not want to read one txt and create another with removing line. I want to delete line from my existing txt. thanks.


Solution

  • This is a pretty tricky problem, despite it looking a trivial one. In case of variable lines length, maybe your only option is reading the file line by line to indentify offset and length of the target line. Then copying the following portion of the file starting at offset, eventually truncating the file lenght to its original size minus the the target line's length. I use a RandomAccessFile to access the internal pointer and also read by lines.

    This program requires two command line arguments:

    • args[0] is the filename
    • args[1] is the target line number (1-based: first line is #1)
    public class RemoveLine {
        public static void main(String[] args) throws IOException {
            // Use a random access file
            RandomAccessFile file = new RandomAccessFile(args[0], "rw");
            int counter = 0, target = Integer.parseInt(args[1]);
            long offset = 0, length = 0;
    
            while (file.readLine() != null) {
                counter++;
                if (counter == target)
                    break; // Found target line's offset
                offset = file.getFilePointer();
            }
    
            length = file.getFilePointer() - offset;
    
            if (target > counter) {
                file.close();
                throw new IOException("No such line!");
            }
    
            byte[] buffer = new byte[4096];
            int read = -1; // will store byte reads from file.read()
            while ((read = file.read(buffer)) > -1){
                file.seek(file.getFilePointer() - read - length);
                file.write(buffer, 0, read);
                file.seek(file.getFilePointer() + length);
            }
            file.setLength(file.length() - length); //truncate by length
            file.close();
        }
    }
    

    Here is the full code, including a JUnit test case. The advantage of using this solution is that it should be fully scalable with respect to memory, ie since it uses a fixed buffer, its memory requirements are predictable and don't change according to the input file size.