FilterReader Masks Digits On Read

Extend FilterReader to mask digits during reads; override the bulk read too because FilterReader forwards it to the underlying stream and would skip the mask.

JavaSecurity Boundaries

Code

snippet
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class DigitMaskingReader extends FilterReader {

    DigitMaskingReader(Reader in) {
        super(in);
    }

    // 单字符读取:mask digits,一律换成占位符
    @Override
    public int read() throws IOException {
        int c = super.read();
        return (c >= '0' && c <= '9') ? '*' : c;
    }

    // FilterReader 的数组版 read 直接转发底层流,必须一并覆盖,
    // 否则批量读取会绕过 masks 逻辑
    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
        int n = super.read(cbuf, off, len);
        if (n > 0) {
            for (int i = off; i < off + n; i++) {
                if (cbuf[i] >= '0' && cbuf[i] <= '9') {
                    cbuf[i] = '*';
                }
            }
        }
        return n;
    }

    public static void main(String[] args) throws IOException {
        String secret = "account 8817 balance 2500";
        try (DigitMaskingReader masked = new DigitMaskingReader(new StringReader(secret))) {
            char[] buffer = new char[64];
            int n = masked.read(buffer, 0, buffer.length);
            System.out.println("masked: " + new String(buffer, 0, n));
        }
        // 底层 StringReader 原文不受影响
        System.out.println("source: " + secret);
    }
}

What the code does

FilterReader Masks Digits On Read is built around the class DigitMaskingReader.

The loop for (int i = off; i < off + n; i++) is the only repeated construct. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Watch out for

  • Nothing needs adding to the project before it runs.

Using it

The output comes back labeled — masked:, source: — when the file runs.

The key statements, annotated

return (c >= '0' && c <= '9') ? '*' : c;

Interactive Tools for This Topic

FAQ

What does FilterReader Masks Digits On Read print when run?
The script runs standalone; its 2 labeled outputs include `masked:`, `source:`.