Chr*_*III 62 java arrays size inputstream
我目前的情况是:我必须读取文件并将内容放入InputStream.之后我需要把它的内容InputStream放到一个字节数组中,这个数组需要(据我所知)的大小InputStream.有任何想法吗?
根据要求,我将显示我从上传文件创建的输入流
InputStream uploadedStream = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
java.util.List items = upload.parseRequest(request);
java.util.Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
uploadedStream = item.getInputStream();
//CHANGE uploadedStreambyte = item.get()
}
}
Run Code Online (Sandbox Code Playgroud)
该请求是一个HttpServletRequest对象,它是象FileItemFactory和ServletFileUpload是从Apache通用FileUpload包.
W. *_*eed 42
这是一个真正的老线程,但当我搜索问题时,它仍然是第一个弹出的东西.所以我只是想补充一下:
InputStream inputStream = conn.getInputStream();
int length = inputStream.available();
Run Code Online (Sandbox Code Playgroud)
为我工作.而且比这里的其他答案简单得多.
Bri*_*new 35
我会读入ByteArrayOutputStream然后调用toByteArray()来获取结果字节数组.您不需要提前定义大小(尽管如果您知道它可能是一个优化.在许多情况下您不会)
And*_*ffy 19
如果不读取它,您无法确定流中的数据量; 但是,您可以询问文件的大小:
http://java.sun.com/javase/6/docs/api/java/io/File.html#length()
如果无法做到这一点,您可以将从输入流中读取的字节写入ByteArrayOutputStream,它将根据需要增长.
对于InputStream
org.apache.commons.io.IoUtils.toByteArray(inputStream).length
Run Code Online (Sandbox Code Playgroud)
对于可选的<MultipartFile>
Stream.of(multipartFile.get()).mapToLong(file->file.getSize()).findFirst().getAsLong()
Run Code Online (Sandbox Code Playgroud)
下面的函数应该适用于任何InputStream. 正如其他答案所暗示的那样,如果不通读它,您就无法可靠地找到 an 的长度InputStream,但与其他答案不同,您不应尝试通过读入 a 将整个流保存在内存中ByteArrayOutputStream,也没有任何理由这样做。理想情况下,您应该依赖其他 API 来获取流大小,而不是读取流,例如使用 API 获取文件的大小File。
public static int length(InputStream inputStream, int chunkSize) throws IOException {
byte[] buffer = new byte[chunkSize];
int chunkBytesRead = 0;
int length = 0;
while((chunkBytesRead = inputStream.read(buffer)) != -1) {
length += chunkBytesRead;
}
return length;
}
Run Code Online (Sandbox Code Playgroud)
chunkSize选择适合该类型的合理值InputStream。例如,从磁盘读取,如果 的值太小,效率会很低chunkSize。
| 归档时间: |
|
| 查看次数: |
181905 次 |
| 最近记录: |