xhl*_*ill 2 java inputstream outputstream fileinputstream fileoutputstream
在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);
}
Run Code Online (Sandbox Code Playgroud)
两种选择:
继续阅读和写作,直到到达输入的末尾或复制了足够的内容:
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();
}
Run Code Online (Sandbox Code Playgroud)一次调用将所有 5M 读入内存,例如使用DataInputStream.readFully,然后一次性将其写出。更简单,但显然使用更多内存。
| 归档时间: |
|
| 查看次数: |
6936 次 |
| 最近记录: |