Find a line in a file and remove it

后端 未结 16 1851
谎友^
谎友^ 2020-11-22 13:06

I\'m looking for a small code snippet that will find a line in file and remove that line (not content but line) but could not find. So for example I have in a file following

16条回答
  •  情深已故
    2020-11-22 13:47

    Here you go. This solution uses a DataInputStream to scan for the position of the string you want replaced and uses a FileChannel to replace the text at that exact position. It only replaces the first occurrence of the string that it finds. This solution doesn't store a copy of the entire file somewhere, (either the RAM or a temp file), it just edits the portion of the file that it finds.

    public static long scanForString(String text, File file) throws IOException {
        if (text.isEmpty())
            return file.exists() ? 0 : -1;
        // First of all, get a byte array off of this string:
        byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);
    
        // Next, search the file for the byte array.
        try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
    
            List matches = new LinkedList<>();
    
            for (long pos = 0; pos < file.length(); pos++) {
                byte bite = dis.readByte();
    
                for (int i = 0; i < matches.size(); i++) {
                    Integer m = matches.get(i);
                    if (bytes[m] != bite)
                        matches.remove(i--);
                    else if (++m == bytes.length)
                        return pos - m + 1;
                    else
                        matches.set(i, m);
                }
    
                if (bytes[0] == bite)
                    matches.add(1);
            }
        }
        return -1;
    }
    
    public static void replaceText(String text, String replacement, File file) throws IOException {
        // Open a FileChannel with writing ability. You don't really need the read
        // ability for this specific case, but there it is in case you need it for
        // something else.
        try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ)) {
            long scanForString = scanForString(text, file);
            if (scanForString == -1) {
                System.out.println("String not found.");
                return;
            }
            channel.position(scanForString);
            channel.write(ByteBuffer.wrap(replacement.getBytes(/* StandardCharsets.your_charset */)));
        }
    }
    

    Example

    Input: ABCDEFGHIJKLMNOPQRSTUVWXYZ

    Method Call:

    replaceText("QRS", "000", new File("path/to/file");
    

    Resulting File: ABCDEFGHIJKLMNOP000TUVWXYZ

提交回复
热议问题