繁体   English   中英

在Java中,如何从输入流中读取固定长度并将其另存为文件?

[英]In java, how to read a fixed length from the inputstream and save as a file?

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

两种选择:

  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 ,然后一次性将其写出。 比较简单,但显然使用更多的内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM