Ric*_*ler 1095
您可以使用Apache Commons IO来处理此类和类似的任务.
该IOUtils类型有一个静态方法来读取InputStream和返回a byte[].
InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
Run Code Online (Sandbox Code Playgroud)
在内部,这会创建一个ByteArrayOutputStream并将字节复制到输出,然后调用toByteArray().它通过复制4KiB块中的字节来处理大文件.
Ada*_*ski 439
您需要从您的每个字节读取InputStream并将其写入a ByteArrayOutputStream.然后,您可以通过调用检索基础字节数组toByteArray(); 例如
InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
Run Code Online (Sandbox Code Playgroud)
Hol*_*ger 280
最后,二十年后,有了一个简单的解决方案,而不需要第三方库,这要归功于Java 9:
InputStream is;
…
byte[] array = is.readAllBytes();
Run Code Online (Sandbox Code Playgroud)
还要注意便利方法readNBytes(byte[] b, int off, int len)和transferTo(OutputStream)解决重复需求.
der*_*itz 126
使用vanilla Java DataInputStream及其readFully方法(至少从Java 1.4开始存在):
...
byte[] bytes = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(bytes);
...
Run Code Online (Sandbox Code Playgroud)
这种方法还有其他一些风格,但我一直都在使用这个用例.
ber*_*tie 116
如果您碰巧使用谷歌番石榴,它将如此简单:
byte[] bytes = ByteStreams.toByteArray(inputStream);
Run Code Online (Sandbox Code Playgroud)
oli*_*rkn 40
public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[0xFFFF];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
os.write(buffer, 0, len);
}
return os.toByteArray();
}
Run Code Online (Sandbox Code Playgroud)
Jes*_*per 19
你真的需要这个形象byte[]吗?您对byte[]图像文件的完整内容有何期待- 以图像文件所处的格式编码,或RGB像素值?
这里的其他答案向您展示如何将文件读入byte[].您byte[]将包含文件的确切内容,并且您需要解码它以对图像数据执行任何操作.
Java用于读取(和写入)图像的标准API是ImageIO API,您可以在包中找到它javax.imageio.您只需一行代码即可从文件中读取图像:
BufferedImage image = ImageIO.read(new File("image.jpg"));
Run Code Online (Sandbox Code Playgroud)
这会给你一个BufferedImage,而不是一个byte[].要获取的图像数据,可以调用getRaster()的BufferedImage.这将为您提供一个Raster对象,该对象具有访问像素数据的方法(它有几个getPixel()/ getPixels()方法).
查找API文档javax.imageio.ImageIO,java.awt.image.BufferedImage,java.awt.image.Raster等.
默认情况下,ImageIO支持多种图像格式:JPEG,PNG,BMP,WBMP和GIF.可以添加对更多格式的支持(您需要一个实现ImageIO服务提供程序接口的插件).
另请参阅以下教程:使用图像
Mir*_*ili 16
安全的解决方案(具有close正确的流功能):
Java 9+版本:
final byte[] bytes;
try (inputStream) {
bytes = inputStream.readAllBytes();
}
Run Code Online (Sandbox Code Playgroud)Java 8版本:
public static byte[] readAllBytes(InputStream inputStream) throws IOException {
final int bufLen = 4 * 0x400; // 4KB
byte[] buf = new byte[bufLen];
int readLen;
IOException exception = null;
try {
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)Kotlin版本(无法访问Java 9+时):
@Throws(IOException::class)
fun InputStream.readAllBytes(): ByteArray {
val bufLen = 4 * 0x400 // 4KB
val buf = ByteArray(bufLen)
var readLen: Int = 0
ByteArrayOutputStream().use { o ->
this.use { i ->
while (i.read(buf, 0, bufLen).also { readLen = it } != -1)
o.write(buf, 0, readLen)
}
return o.toByteArray()
}
}
Run Code Online (Sandbox Code Playgroud)
为避免嵌套,use请参见此处。
Kri*_*jic 14
如果您不想使用Apache commons-io库,则此片段取自sun.misc.IOUtils类.它几乎是使用ByteBuffers的常见实现的两倍:
public static byte[] readFully(InputStream is, int length, boolean readAll)
throws IOException {
byte[] output = {};
if (length == -1) length = Integer.MAX_VALUE;
int pos = 0;
while (pos < length) {
int bytesToRead;
if (pos >= output.length) { // Only expand when there's no room
bytesToRead = Math.min(length - pos, output.length + 1024);
if (output.length < pos + bytesToRead) {
output = Arrays.copyOf(output, pos + bytesToRead);
}
} else {
bytesToRead = output.length - pos;
}
int cc = is.read(output, pos, bytesToRead);
if (cc < 0) {
if (readAll && length != Integer.MAX_VALUE) {
throw new EOFException("Detect premature EOF");
} else {
if (output.length != pos) {
output = Arrays.copyOf(output, pos);
}
break;
}
}
pos += cc;
}
return output;
}
Run Code Online (Sandbox Code Playgroud)
har*_*h_v 14
在某些情况下有人仍在寻找没有依赖关系的解决方案,如果你有一个文件.
1)DataInputStream
byte[] data = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(data);
dis.close();
Run Code Online (Sandbox Code Playgroud)
2)ByteArrayOutputStream
InputStream is = new FileInputStream(file);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[(int) file.length()];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
Run Code Online (Sandbox Code Playgroud)
3)RandomAccessFile
RandomAccessFile raf = new RandomAccessFile(file, "r");
byte[] data = new byte[(int) raf.length()];
raf.readFully(data);
Run Code Online (Sandbox Code Playgroud)
Yul*_*ney 10
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (true) {
int r = in.read(buffer);
if (r == -1) break;
out.write(buffer, 0, r);
}
byte[] ret = out.toByteArray();
Run Code Online (Sandbox Code Playgroud)
小智 8
Input Stream is ...
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = in.read();
while (next > -1) {
bos.write(next);
next = in.read();
}
bos.flush();
byte[] result = bos.toByteArray();
bos.close();
Run Code Online (Sandbox Code Playgroud)
@Adamski:你可以完全避免缓冲.
代码复制http://www.exampledepot.com/egs/java.io/File2ByteArray.html(是的,这是很详细,但需要的内存与其他解决方案的一半.)
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
Run Code Online (Sandbox Code Playgroud)
Java 9 最终会给你一个很好的方法:
InputStream in = ...;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
in.transferTo( bos );
byte[] bytes = bos.toByteArray();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
901254 次 |
| 最近记录: |