how can I delete line from txt?

倾然丶 夕夏残阳落幕 提交于 2019-12-09 22:58:54

问题


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.


回答1:


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.




回答2:


Try storing file into a String buffer replace what you intend to replace, then replace the contents of the file entirely.




回答3:


You can delete a line by copying the rest of the data in the file, then flushing the file and finally writing the copied data.Thr following code searches for the string to be deleted and skips the code to copy in a stringBuider . The contents of stringBuilder are copied to the same file after flushing

         try {
                InputStream inputStream = openFileInput(FILENAME);
                FileOutputStream fos = openFileOutput("temp", Context.MODE_APPEND);

                if (inputStream != null) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String receiveString = "";
                    String deleteString = "<string you want to del>";
                    StringBuilder stringBuilder = new StringBuilder();

                    while ((receiveString = bufferedReader.readLine()) != null) {
                        if (!reciveString.equals(deleteline)) {
                            stringBuilder.append(receiveString);
                        }
                    }
                    fos.flush();

                    fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fos.write(stringBuilder.toString().getBytes());
                    fos.close();
                    inputStream.close();
                   }


来源:https://stackoverflow.com/questions/12652706/how-can-i-delete-line-from-txt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!