在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);
}
最佳答案
两个选项:
继续阅读和写作,直到到达输入的末尾或复制了足够的内容:
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(); }
一次调用将所有 5M 数据读入内存,例如使用
DataInputStream.readFully
,然后一口气写出来。更简单,但显然使用更多内存。
关于java - 在java中,如何从输入流中读取固定长度并保存为文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7976332/