Java 确定 InputStream 的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1119332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determine the size of an InputStream
提问by ChronoXIII
My current situation is: I have to read a file and put the contents into InputStream
. Afterwards I need to place the contents of the InputStream
into a byte array which requires (as far as I know) the size of the InputStream
. Any ideas?
我目前的情况是:我必须读取一个文件并将内容放入InputStream
. 之后我需要将 的内容InputStream
放入一个字节数组中,该数组需要(据我所知)InputStream
. 有任何想法吗?
As requested, I will show the input stream that I am creating from an uploaded file
根据要求,我将显示我从上传的文件创建的输入流
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()
}
}
The request is a HttpServletRequest
object, which is like the FileItemFactory
and ServletFileUpload
is from the Apache Commons FileUpload package.
请求是一个HttpServletRequest
对象,它类似于FileItemFactory
并且ServletFileUpload
来自 Apache Commons FileUpload 包。
采纳答案by akarnokd
I just wanted to add, Apache Commons IO has stream support utilities to perform the copy. (Btw, what do you mean by placing the file into an inputstream? Can you show us your code?)
我只想补充一点,Apache Commons IO 具有流支持实用程序来执行复制。(顺便说一句,将文件放入输入流是什么意思?你能告诉我们你的代码吗?)
Edit:
编辑:
Okay, what do you want to do with the contents of the item?
There is an item.get()
which returnsthe entire thing in a byte array.
好的,您想如何处理该项目的内容?有一个item.get()
返回字节数组中的整个内容。
Edit2
编辑2
item.getSize()
will return the uploaded file size.
item.getSize()
将返回上传的文件大小。
回答by Andrew Duffy
You can't determine the amount of data in a stream without reading it; you can, however, ask for the size of a file:
不读取就无法确定流中的数据量;但是,您可以询问文件的大小:
http://java.sun.com/javase/6/docs/api/java/io/File.html#length()
http://java.sun.com/javase/6/docs/api/java/io/File.html#length()
If that isn't possible, you can write the bytes you read from the input stream to a ByteArrayOutputStreamwhich will grow as required.
如果这是不可能的,您可以将从输入流中读取的字节写入ByteArrayOutputStream,它将根据需要增长。
回答by Brian Agnew
I would read into a ByteArrayOutputStreamand then call toByteArray()to get the resultant byte array. You don't need to define the size in advance (although it's possibly an optimisation if you know it. In many cases you won't)
我会读入一个ByteArrayOutputStream然后调用toByteArray()来获取结果字节数组。您不需要提前定义大小(尽管如果您知道它可能是一种优化。在许多情况下您不会)
回答by Gnanam R
you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link
您可以使用 Utils.java 的 getBytes(inputStream) 获取 InputStream 的大小,请查看以下链接
回答by W. B. Reed
This is a REALLY old thread, but it was still the first thing to pop up when I googled the issue. So I just wanted to add this:
这是一个非常古老的线程,但是当我用谷歌搜索这个问题时,它仍然是第一个弹出的东西。所以我只想添加这个:
InputStream inputStream = conn.getInputStream();
int length = inputStream.available();
Worked for me. And MUCH simpler than the other answers here.
为我工作。而且比这里的其他答案简单得多。
WarningThis solution does not provide reliable results regarding the total size of a stream. Except from the JavaDoc:
警告此解决方案无法提供有关流总大小的可靠结果。除了 JavaDoc:
Note that while some implementations of {@code InputStream} will return * the total number of bytes in the stream, many will not.
请注意,虽然 {@code InputStream} 的某些实现将返回 * 流中的总字节数,但许多不会。
回答by Carlos.V
Use this method, you just have to pass the InputStream
使用这个方法,你只需要传递 InputStream
public String readIt(InputStream is) {
if (is != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
return sb.toString();
}
return "error: ";
}
回答by Sverrir Sigmundarson
When explicitly dealing with a ByteArrayInputStream
then contrary to some of the comments on this page you can use the .available()
function to get the size. Just have to do it before you start reading from it.
当显式处理ByteArrayInputStream
then 与此页面上的一些评论相反时,您可以使用该.available()
函数来获取大小。只需要在开始阅读它之前做它。
From the JavaDocs:
来自 JavaDocs:
Returns the number of remaining bytes that can be read (or skipped over) from this input stream. The value returned is count - pos, which is the number of bytes remaining to be read from the input buffer.
返回可以从此输入流读取(或跳过)的剩余字节数。返回的值是 count - pos,这是要从输入缓冲区读取的剩余字节数。
https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html#available()
https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html#available()
回答by Ashnet
try {
InputStream connInputStream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
int size = connInputStream.available();
int available () 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.
int available () 返回可以从该输入流读取(或跳过)的字节数的估计值,而不会被该输入流的下一次调用方法阻塞。下一次调用可能是同一个线程或另一个线程。单次读取或跳过这么多字节不会阻塞,但可能读取或跳过更少的字节。
回答by amstegraf
For InputStream
对于输入流
org.apache.commons.io.IoUtils.toByteArray(inputStream).length
For Optional < MultipartFile >
对于 Optional < MultipartFile >
Stream.of(multipartFile.get()).mapToLong(file->file.getSize()).findFirst().getAsLong()
回答by Travis Parks
If you know that your InputStream
is a FileInputStream
or a ByteArrayInputStream
, you can use a little reflection to get at the stream size without reading the entire contents. Here's an example method:
如果您知道您InputStream
是 aFileInputStream
或 a ByteArrayInputStream
,您可以使用一点反射来获得流大小,而无需阅读整个内容。这是一个示例方法:
static long getInputLength(InputStream inputStream) {
try {
if (inputStream instanceof FilterInputStream) {
FilterInputStream filtered = (FilterInputStream)inputStream;
Field field = FilterInputStream.class.getDeclaredField("in");
field.setAccessible(true);
InputStream internal = (InputStream) field.get(filtered);
return getInputLength(internal);
} else if (inputStream instanceof ByteArrayInputStream) {
ByteArrayInputStream wrapper = (ByteArrayInputStream)inputStream;
Field field = ByteArrayInputStream.class.getDeclaredField("buf");
field.setAccessible(true);
byte[] buffer = (byte[])field.get(wrapper);
return buffer.length;
} else if (inputStream instanceof FileInputStream) {
FileInputStream fileStream = (FileInputStream)inputStream;
return fileStream.getChannel().size();
}
} catch (NoSuchFieldException | IllegalAccessException | IOException exception) {
// Ignore all errors and just return -1.
}
return -1;
}
This could be extended to support additional input streams, I am sure.
我敢肯定,这可以扩展以支持额外的输入流。