When directly subclassing java.io.OutputStream
or java.io.FilterOutputStream
, the only requirement is that you implement
the method write(int)
. However most uses for such streams don’t write a single byte at a time and the default implementation for
write(byte[],int,int)
will call write(int)
for every single byte in the array which can create a lot of overhead and is
utterly inefficient. It is therefore strongly recommended that subclasses provide an efficient implementation of
write(byte[],int,int)
.
This rule raises an issue when a direct subclass of java.io.OutputStream
or java.io.FilterOutputStream
doesn’t provide an
override of write(byte[],int,int)
.
Noncompliant code example
public class MyStream extends OutputStream { // Noncompliant
private FileOutputStream fout;
public MyStream(File file) throws IOException {
fout = new FileOutputStream(file);
}
@Override
public void write(int b) throws IOException {
fout.write(b);
}
@Override
public void close() throws IOException {
fout.write("\n\n".getBytes());
fout.close();
super.close();
}
}
Compliant solution
public class MyStream extends OutputStream {
private FileOutputStream fout;
public MyStream(File file) throws IOException {
fout = new FileOutputStream(file);
}
@Override
public void write(int b) throws IOException {
fout.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
fout.write(b, off, len);
}
@Override
public void close() throws IOException {
fout.write("\n\n".getBytes());
fout.close();
super.close();
}
}
Exceptions
This rule doesn’t raise an issue when the class is declared abstract
.