在java中,如何从输入流中读取固定长度并保存为文件?
在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);
}
In java, how to read a fixed length from the inputstream and save as a file?
eg. I want to read 5M from inputStream, and save as downloadFile.txt or whatever.(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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两个选项:
继续阅读和写作,直到到达输入的末尾或复制了足够的内容:
一次调用将所有 5M 数据读入内存,例如使用
DataInputStream.readFully< /code>,然后一口气写出来。更简单,但明显占用更多内存。
Two options:
Just keep reading and writing until you either reach the end of the input or you've copied enough:
Read all 5M into memory in one call, e.g. using
DataInputStream.readFully
, and then write it out in one go. Simpler, but obviously uses more memory.