Flo*_*tis 3 java inputstream java-8
我写了一个程序,得到所有字节来自InputStream于Java的9与
InputStream.readAllBytes()
Run Code Online (Sandbox Code Playgroud)
现在,我想将其导出到Java 1.8 及以下版本。有等价的功能吗?找不到一个。
read您可以使用这样的 好旧方法:
public static byte[] readAllBytes(InputStream inputStream) throws IOException {
final int bufLen = 1024;
byte[] buf = new byte[bufLen];
int readLen;
IOException exception = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while ((readLen = inputStream.read(buf, 0, bufLen)) != -1)
outputStream.write(buf, 0, readLen);
return outputStream.toByteArray();
} catch (IOException e) {
exception = e;
throw e;
} finally {
if (exception == null) inputStream.close();
else try {
inputStream.close();
} catch (IOException e) {
exception.addSuppressed(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
InputStream.readAllBytes() 可用,因为 java 9 而不是 java 7 ...
除此之外,您可以(无第三方):
byte[] bytes = new byte[(int) file.length()];
DataInputStream dataInputStream = new DataInputStream(new FileInputStream(file));
dataInputStream .readFully(bytes);
Run Code Online (Sandbox Code Playgroud)
或者,如果您不介意使用第三方(Commons IO):
byte[] bytes = IOUtils.toByteArray(is);
Run Code Online (Sandbox Code Playgroud)
番石榴还有助于:
byte[] bytes = ByteStreams.toByteArray(inputStream);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5395 次 |
| 最近记录: |