All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.conqat.lib.commons.io.LimitedWriter Maven / Gradle / Ivy

There is a newer version: 2024.7.2
Show newest version
/*
 * Copyright (c) CQSE GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.conqat.lib.commons.io;

import static java.util.Objects.requireNonNull;

import java.io.IOException;
import java.io.Writer;

/**
 * A {@link Writer} that delegates to another {@link Writer} until a given maximum number of
 * characters has been written. It then writes a final ellipsis and stops delegating.
 */
public class LimitedWriter extends Writer {

	private final Writer delegate;

	/**
	 * The number of remaining characters that can still be {@linkplain #write(char[], int, int)
	 * written} until the limit is reached. A value of {@code -1} denotes the fact the final ellipsis
	 * has already been written to the {@link #delegate}.
	 */
	private int charsRemaining;

	public LimitedWriter(Writer delegate, int maxChars) {
		if (maxChars < 0) {
			throw new IllegalArgumentException("Negative number of maximum characters");
		}
		this.delegate = requireNonNull(delegate);
		this.charsRemaining = maxChars;
	}

	@Override
	public void write(char[] buffer, int offset, int length) throws IOException {
		if (charsRemaining >= length) {
			delegate.write(buffer, offset, length);
			charsRemaining -= length;
		} else if (charsRemaining >= 0) {
			delegate.write(buffer, offset, charsRemaining);
			delegate.write("[...]");
			charsRemaining = -1;
		}
	}

	@Override
	public void flush() throws IOException {
		delegate.flush();
	}

	@Override
	public void close() throws IOException {
		delegate.close();
	}

	@Override
	public String toString() {
		return delegate.toString();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy