【问题标题】:In java, how to read a fixed length from the inputstream and save as a file?在java中,如何从输入流中读取固定长度并保存为文件?
【发布时间】:2011-11-02 05:53:14
【问题描述】:

在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);
}

【问题讨论】:

  • 继续读写,直到得到5M——你知道读了多少字节;使用数学。
  • inputStream.read(buffer,0,1024);会这样做。读到一个计数,所以你得到 5MB:)
  • @Krishnanunni 实际上,甚至不需要——read(byte[] buf) 将尝试读取 buf.length 字节。
  • @DaveNewton:但是如果您只剩下 10 个字节要读取怎么办?您可能不想再从输入流中读取任何内容,为此必须创建一个额外的缓冲区很痛苦。
  • @JonSkeet It attempts to read buf.length bytes, and returns the number actually read. 它调用 read(buf, off, len),它调用 read();他们都在 EOF 停止阅读。

标签: java inputstream outputstream fileinputstream fileoutputstream


【解决方案1】:

两种选择:

  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,然后一口气写出来。更简单,但显然占用更多内存。

【讨论】:

  • 它非常适合它的要求。但是,我有一个稍微不同的情况。我有一个很大的日志文件,需要拆分为 5MB 的文件。
  • @J.Tribbiani:那么我建议你问一个不同的问题,提供更多细节。
猜你喜欢
  • 2019-07-28
  • 1970-01-01
  • 2016-02-08
  • 1970-01-01
  • 2015-04-20
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 2013-07-16
相关资源
最近更新 更多