FilterOutputStream
A filter output stream takes the data passed to its write() methods, filters it, and writes the filtered data to an underlying output stream.
Filter output streams are created from subclasses of the concrete FilterOutputStream class, an OutputStream subclass.
The following code extends FilterOutputStream.
import java.io.FileInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Main {
public static void main(String[] args) throws Exception {
InputStream in = new FileInputStream("test.txt");
OutputStream out = System.out;
PrintableOutputStream pout = new PrintableOutputStream(out);
for (int c = in.read(); c != -1; c = in.read()) {
pout.write(c);
}
out.close();
}
}
class PrintableOutputStream extends FilterOutputStream {
public PrintableOutputStream(OutputStream out) {
super(out);
}
public void write(int b) throws IOException {
// carriage return, linefeed, and tab
if (b == '\n' || b == '\r' || b == '\t')
out.write(b);
// non-printing characters
else if (b < 32 || b > 126)
out.write('?');
// printing, ASCII characters
else
out.write(b);
}
public void write(byte[] data, int offset, int length) throws IOException {
for (int i = offset; i < offset + length; i++) {
this.write(data[i]);
}
}
}
BufferedOutputStream is a subclass of FilterOutputStream.
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(
"yourFile.txt"));
bufferedOutput.write("Line one".getBytes());
bufferedOutput.write("\n".getBytes());
bufferedOutput.write(65);
bufferedOutput.close();
}
}