簡體   English   中英

如何將inputstream的內容復制或存儲到字節數組中?

[英]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);

有關詳細信息,請參見

的InputStream

DataInputStream類

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM