de.audioattack.io.CharacterDevice Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of console Show documentation
Show all versions of console Show documentation
A replacement for java.io.Console with a System.in and System.out based fallback
The newest version!
/*
* SPDX-FileCopyrightText: 2018 Marc Nause
*
* SPDX-License-Identifier: Apache-2.0
*/
package de.audioattack.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Objects;
/**
* Console which is based on provided readers and writers.
*/
public class CharacterDevice implements Console {
private final BufferedReader reader;
private final PrintWriter writer;
/**
* Constructor.
*
* @param reader used to read characters, must not be {@code null}
* @param writer used to write characters, must not be {@code null}
*/
CharacterDevice(final BufferedReader reader, final PrintWriter writer) {
this.reader = Objects.requireNonNull(reader, "reader must not be ");
this.writer = Objects.requireNonNull(writer, "writer must not be ");
}
/**
* {@inheritDoc}
*/
@Override
public Reader reader() {
return new UncloseableReader(reader);
}
/**
* {@inheritDoc}
*/
@Override
public PrintWriter writer() {
return new UncloseablePrintWriter(writer);
}
/**
* {@inheritDoc}
*/
@Override
public Console format(final String fmt, final Object... args) {
writer.format(fmt, args);
flush();
return this;
}
/**
* {@inheritDoc}
*/
@Override
public Console printf(final String fmt, final Object... args) {
return format(fmt, args);
}
/**
* {@inheritDoc}
*/
@Override
public String readLine(final String fmt, final Object... args) {
format(fmt, args);
return readLine();
}
/**
* {@inheritDoc}
*/
@Override
public String readLine() {
try {
return reader.readLine();
} catch (final IOException e) {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public char[] readPassword(final String fmt, final Object... args) {
format("WARNING! Password will be visible in the command line!%n");
return toCharArray(readLine(fmt, args));
}
/**
* {@inheritDoc}
*/
@Override
public char[] readPassword() {
return readPassword("");
}
/**
* {@inheritDoc}
*/
@Override
public void flush() {
writer.flush();
}
private static char[] toCharArray(final String readLine) {
return readLine == null ? null : readLine.toCharArray();
}
}