2

在java中,如何从输入流中读取固定长度并保存为文件?例如。我想从 inputStream 中读取 5M,并保存为 downloadFile.txt 或其他。(BUFFERSIZE=1024)

FileOutputStream fos = new FileOutputStream(downloadFile);
byte buffer [] = new byte[BUFFERSIZE];
int temp = 0;
while ((temp = inputStream.read(buffer)) != -1)
{
    fos.write(buffer, 0, temp);
}
4

1 回答 1

5

两种选择:

  1. 继续阅读和写作,直到你到达输入的末尾或者你已经复制了足够多的内容:

    byte[] buffer = new byte[1024];
    int bytesLeft = 5 * 1024 * 1024; // Or whatever
    FileInputStream fis = new FileInputStream(input);
    try {
      FileOutputStream fos = new FileOutputStream(output);
      try {
        while (bytesLeft > 0) {
          int read = fis.read(buffer, 0, Math.min(bytesLeft, buffer.length);
          if (read == -1) {
            throw new EOFException("Unexpected end of data");
          }
          fos.write(buffer, 0, read);
          bytesLeft -= read;
        }
      } finally {
        fos.close(); // Or use Guava's Closeables.closeQuietly,
                     // or try-with-resources in Java 7
      }
    } finally {
      fis.close(); 
    }
    
  2. 一次调用将所有 5M 读入内存,例如使用DataInputStream.readFully,然后一口气将其写出。更简单,但显然使用更多内存。

于 2011-11-02T06:27:56.087 回答