[英]How to copy or store the contents of inputstream in to byte array?
我正在使用Apache Commons FileUpload库上传文件。 我想将InputStream的内容复制到一个单字节数组中。 我该怎么办?
try {
List<FileItem> items = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input
// type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
out.println("returned");
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream input = item.getInputStream();
if (fieldname.equals("file")) {
// please help me here.
byte[] allbyte = ???
}
}
}
}
使用Apache commons-io库中的IOUtils.toByteArray()
实用程序方法:
import org.apache.commons.io.IOUtils;
InputStream input;
byte[] bytes = IOUtils.toByteArray(input);
它为您提供了一线。 通常,尝试找到一个可以满足您需求的现有库,并且Apache commons库包含许多方便的方法。
如何使用ByteArrayOutputStream
呢?
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b = input.read();
while (b != -1) {
out.write(b);
b = input.read();
}
allbyte = out.toByteArray();
使用DataInputStream。 它具有readFully()方法,该方法读取所有字节。
DataInputStream dis = new DataInputStream(inputStream);
byte[] allBytes = new byte[inputStream.available()];
dis.readFully(allBytes);
有关详细信息,请参见
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.