java的InputStream獲取字節(jié)大小相關(guān)方法
1 通過StreamUtils工具類的copyToByteArray()方法獲?。ㄍ扑])
正常大部分項(xiàng)目都是使用的Spring,而Spring已經(jīng)幫我們開發(fā)好了相應(yīng)的工具類,我們直接調(diào)用即可。
InputStream is = this.getClass().getResourceAsStream(filePath);
byte[] bytes = StreamUtils.copyToByteArray(is);
is.read(bytes);
2 通過available()方法獲?。ú煌扑])
InputStream is = this.getClass().getResourceAsStream(filePath);
byte[] bytes = new byte[is.available()];
is.read(bytes);
2.1 不推薦理由
可以看一下方法注釋:文章來源:http://www.zghlxwxcb.cn/news/detail-726585.html
/** * Returns an estimate of the number of bytes that can be read (or * skipped over) from this input stream without blocking by the next * invocation of a method for this input stream. The next invocation * might be the same thread or another thread. A single read or skip of this * many bytes will not block, but may read or skip fewer bytes. * * <p> Note that while some implementations of {@code InputStream} will return * the total number of bytes in the stream, many will not. It is * never correct to use the return value of this method to allocate * a buffer intended to hold all data in this stream. * * <p> A subclass' implementation of this method may choose to throw an * {@link java.io.IOException} if this input stream has been closed by * invoking the {@link #close()} method. * * <p> The {@code available} method for class {@code InputStream} always * returns {@code 0}. * * <p> This method should be overridden by subclasses. * * @return ? ? an estimate of the number of bytes that can be read (or skipped * ? ? ? ? ? ? over) from this input stream without blocking or {@code 0} when * ? ? ? ? ? ? it reaches the end of the input stream. * @exception java.io.IOException if an I/O error occurs. */
大致意思是返回的字節(jié)數(shù)可能由于網(wǎng)絡(luò)原因阻塞一次只能返回部分字節(jié)或者另外一個(gè)線程也讀了導(dǎo)致返回部分字節(jié),也就是說如果使用available()方法去獲取InputStream的長(zhǎng)度來作為字節(jié)數(shù)組的長(zhǎng)度,那可能會(huì)出現(xiàn)字節(jié)接受不完整的錯(cuò)誤,所以不推薦使用該方法的返回值去分配一個(gè)緩沖的byte數(shù)組。文章來源地址http://www.zghlxwxcb.cn/news/detail-726585.html
3 通過file.length()來獲取
File file = new File(path);
InputStream stream = new FileInputStream(file);
byte[] bytes = new byte[file.length()]
到了這里,關(guān)于java的InputStream獲取字節(jié)大小相關(guān)方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!