Come illustrato di seguito, esistono due modi semplici per eseguire una copiatrice di flussi (barra che introduce Apache Commons o simili). Quale dovrei andare a fare, e perché?Progettazione del metodo statico rispetto all'oggetto
public class StreamCopier {
private int bufferSize;
public StreamCopier() {
this(4096);
}
public StreamCopier(int bufferSize) {
this.bufferSize = bufferSize;
}
public long copy(InputStream in , OutputStream out) throws IOException{
byte[] buffer = new byte[bufferSize];
int bytesRead;
long totalBytes = 0;
while((bytesRead= in.read(buffer)) != -1) {
out.write(buffer,0,bytesRead);
totalBytes += bytesRead;
}
return totalBytes;
}
}
vs
public class StreamCopier {
public static long copy(InputStream in , OutputStream out)
throws IOException {
return this.copy(in,out,4096);
}
public static long copy(InputStream in , OutputStream out,int bufferSize)
throws IOException {
byte[] buffer = new byte[bufferSize];
int bytesRead;
long totalBytes = 0;
while ((bytesRead= in.read(buffer)) != -1) {
out.write(buffer,0,bytesRead);
totalBytes += bytesRead;
}
return totalBytes;
}
}
.. c'è un bug nel primo 'copia' metodo nel secondo esempio: il terzo parametro deve essere eliminato. Forse qualcuno potrebbe applicare un bugfix!? –