InputStream方法提供了read(byte[] b)方法将其内容写入一个byte数组,但是我事先不能知道这个数组的长度,我应该如何将InputStream里面的内容完全写入一个数组中呢?

解决方案 »

  1.   

    我的一个比较笨蛋的方法是:
    List byteList = new ArrayList();
    int byteInt = 0;
    while ((byteInt = inputStream.read()) != -1) {
        byteList.add(new Byte((byte)byteInt));
    }
    byte[] bytes = new byte[byteList.size()];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = ((Byte)byteList.get(i)).byteValue();
    }
    可是这里面用到了List,是不是有点太重量极了……
      

  2.   

    InputStream.available()就是数组的长度!!
      

  3.   

    正好有一个这样的类
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;public class FileByteUtil {
    public static void main(String[] args) throws Exception {
    File file=new File("f:/test.doc");
    byte[] fileByte = file2byte(file);
    byte2file(fileByte, "f:/test2.doc");
    }

    public static byte[] file2byte(File f) throws Exception {
      return file2byte(f.getPath());
    }

    public static byte[] file2byte(String f) throws Exception {
    try {
    InputStream in = new FileInputStream(f);
    byte[] tmp = new byte[512];
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int bytesRead = in.read(tmp);
    while (bytesRead != -1) {
    out.write(tmp, 0, bytesRead);
    bytesRead = in.read(tmp);
    }
    return out.toByteArray();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return null;
    } // writes byte [] to a file
    public static void byte2file(byte[] data, String fn) throws Exception {
    try {
    OutputStream out = new FileOutputStream(fn);
    out.write(data);
    out.flush();
    } catch (FileNotFoundException e) {
    throw e;
    } catch (IOException e) {
    throw e;
    }
    }}
      

  4.   

    int len = in.available();
    byte b = new byte[len];
    in.read(b);
      

  5.   

    InputStream in = getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    org.apache.commons.io.IOUtils.copy(in, out);
    byte[] bytes = out.toByteArray();