Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Inefficient output stream

ID: java/inefficient-output-streamKind: problemSecurity severity: Severity: warningPrecision: very-highTags:   - quality   - reliability   - performance   - efficiencyQuery suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

The classesjava.io.OutputStream andjava.io.FilterOutputStream only require subclasses to implement the methodwrite(byteb). Typically, uses ofOutputStreams will not write single bytes, but an array via thewrite(byte[]b,intoff,intlen) method. The default implementation of this method, which you are not required to override, callswrite(byteb) for each byte in the array. If this method involves I/O, such as accessing the network or disk, this is likely to incur significant overhead.

Recommendation

Always provide an implementation of thewrite(byte[]b,intoff,intlen) method.

Example

The following example shows a subclass ofOutputStream that simply wraps aDigestOutputStream to confirm that the data it writes to a file has the expected MD5 hash. Without an implementation ofwrite(byte[]b,intoff,intlen) this will be very slow, because it makes a call toDigestOutputStream.write(byteb) andFileOutputStream.write(byteb) for each byte written.

publicclassDigestCheckingFileOutputStreamextendsOutputStream{privateDigestOutputStreamdigest;privatebyte[]expectedMD5;publicDigestCheckingFileOutputStream(Filefile,byte[]expectedMD5)throwsIOException,NoSuchAlgorithmException{this.expectedMD5=expectedMD5;digest=newDigestOutputStream(newFileOutputStream(file),MessageDigest.getInstance("MD5"));}@Overridepublicvoidwrite(intb)throwsIOException{digest.write(b);}@Overridepublicvoidclose()throwsIOException{super.close();digest.close();byte[]md5=digest.getMessageDigest().digest();if(expectedMD5!=null&&!Arrays.equals(expectedMD5,md5)){thrownewInternalError();}}}

The example can be updated to use a more efficient method. In this case, calls towrite(byte[]b,intoff,intlen) are simply forwarded toDigestOutputStream.write(byte[]b,intoff,intlen).

publicclassDigestCheckingFileOutputStreamextendsOutputStream{privateDigestOutputStreamdigest;privatebyte[]expectedMD5;publicDigestCheckingFileOutputStream(Filefile,byte[]expectedMD5)throwsIOException,NoSuchAlgorithmException{this.expectedMD5=expectedMD5;digest=newDigestOutputStream(newFileOutputStream(file),MessageDigest.getInstance("MD5"));}@Overridepublicvoidwrite(intb)throwsIOException{digest.write(b);}@Overridepublicvoidwrite(byte[]b,intoff,intlen)throwsIOException{digest.write(b,off,len);}@Overridepublicvoidclose()throwsIOException{super.close();digest.close();byte[]md5=digest.getMessageDigest().digest();if(expectedMD5!=null&&!Arrays.equals(expectedMD5,md5)){thrownewInternalError();}}}

References


[8]ページ先頭

©2009-2025 Movatter.jp