0

我知道有一种方法可以将文件分块转换为字节数组,这是一个示例代码:

 InputStream inputStream = new FileInputStream(videoFile);
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     byte[] b = new byte[1024];
     int bytesRead =0;
     while ((bytesRead = inputStream.read(b)) != -1)
     {
       bos.write(b, 0, bytesRead);
     }

我正在寻找相反的东西:一种将字节数组分块转换为文件的方法。我没有找到任何大块做的例子。

4

3 回答 3

2

您只需要使用类中的write(byte[])orwrite(byte[],int,int)方法即可FileOutputStream

于 2013-09-10T15:35:46.987 回答
1

字节 [] 到文件:

 FileOutputStream fop = null; File file;
        try {
            file = new File(filePath);
            fop = new FileOutputStream(file, true);
            fop.write(chunk);
            fop.flush();
            fop.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                if (fop != null) {
                    fop.close();
                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }

试试这个文件到字节[]:

 InputStream is = new FileInputStream(file);
        int length = (int) file.length();           
        int take = 262144;//size of your chunk
        byte[] bytes = new byte[take];
                    int offset=0;
        int a = 0;
        do {
            a = is.read(bytes, 0, take);
            offset += a;
            //And you can add here each chunk created in to a list, etc, etc.
            //encode to base 64 this is extra :)
            String str = Base64.encodeToString(bytes, Base64.DEFAULT);

        } while (offset < length);=
        is.close();
        is=null;
于 2013-09-10T15:12:31.030 回答
0

考虑概括问题。

此方法以块的形式复制数据:

  public static <T extends OutputStream> T copy(InputStream in, T out)
      throws IOException {
    byte[] buffer = new byte[1024];
    for (int r = in.read(buffer); r != -1; r = in.read(buffer)) {
      out.write(buffer, 0, r);
    }
    return out;
  }

这可以用于读取和读取字节数组:

try (InputStream in = new FileInputStream("original.txt");
    OutputStream out = new FileOutputStream("copy.txt")) {
  byte[] contents = copy(in, new ByteArrayOutputStream()).toByteArray();
  copy(new ByteArrayInputStream(contents), out);
}
于 2013-09-10T15:42:15.157 回答