문제

Java 스트림(입력 또는 출력)에서 즉시 검색 및 바꾸기를 수행하려면 어떻게 해야 합니까?

스트림을 메모리나 파일에 로드하고 싶지 않습니다.

바이트가 지나가는 것을 보고 몇 가지 교체를 수행해야 합니다.교체되는 시퀀스는 짧습니다(최대 20바이트).

도움이 되었습니까?

해결책

제공된 클래스를 사용할 수 있습니다 여기 정적 교체 규칙이 충분한 경우

다른 팁

당신은 결정론적 유한 자동인형 각 바이트를 한 번만 살펴봅니다(예:뒤돌아볼 필요가 없음), 기본적으로 패턴 길이만큼 최대 문자 수를 보유하는 버퍼를 통해 입력을 스트리밍하고 패턴에서 앞으로 나아갈 때 일치하는 패턴을 출력하거나 오버플로(일치하지 않는) 문자를 출력합니다.런타임은 패턴 준비 후 선형입니다.

Wikipedia에는 ​​다음과 같은 정보가 있습니다. 패턴 매칭과 그 작동 방식 이론에 의하면.

나는 제공된 링크에서 좋은 아이디어를 얻었고 스트림에서 $ var $ 변수의 교체를 처리하기 위해 작은 수업을 작성하게되었습니다. 후손 :

public class ReplacingOutputStream extends OutputStream {
    private static final int DOLLAR_SIGN = "$".codePointAt(0);
    private static final int BACKSLASH = "\\".codePointAt(0);
    private final OutputStream delegate;
    private final Map<String, Object> replacementValues;

    private int previous = Integer.MIN_VALUE;
    private boolean replacing = false;
    private ArrayList<Integer> replacement = new ArrayList<Integer>();


    public ReplacingOutputStream(OutputStream delegate, Map<String, Object> replacementValues) {
        this.delegate = delegate;
        this.replacementValues = replacementValues;
    }

    public @Override void write(int b) throws IOException {
        if (b == DOLLAR_SIGN && previous != BACKSLASH) {
            if (replacing) {
                doReplacement();
                replacing = false;
            } else {
                replacing = true;
            }
        } else {
            if (replacing) {
                replacement.add(b);
            } else {
                delegate.write(b);
            }
        }

        previous = b;
    }

    private void doReplacement() throws IOException {
        StringBuilder sb = new StringBuilder();
        for (Integer intval : replacement) {
            sb.append(Character.toChars(intval));
        }
        replacement.clear();

        String oldValue = sb.toString();
        Object _newValue = replacementValues.get(oldValue);
        if (_newValue == null) {
            throw new RuntimeException("Could not find replacement variable for value '"+oldValue+"'.");
        }

        String newValue = _newValue.toString();
        for (int i=0; i < newValue.length(); ++i) {
            int value = newValue.codePointAt(i);
            delegate.write(value);
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top