java - java中用字节写入文件的概念是什么?

标签 java file fileoutputstream

我知道当我想写一个文件时,我应该使用这样的代码:

InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = new FileOutputStream("/sdcard/myfile.jpg");

byte Data[] = new byte[1024];
long total = 0;

while ((count=inputStream.read(Data)) != -1) {
    total = total+count;
    outputStream.write(Data,0,count);
}

但是我不明白这个结果会发生什么,它是在写一个从零到100的图像文件吗?

谁能给我描述一下这是怎么发生的?谢谢

最佳答案

这段代码的作用是将 1024 字节读入临时缓冲区,将它们写入输出,然后重复,用输入中的下一个数据覆盖缓冲区的内容,直到没有更多数据为止。

代码功能的一些分割:

//get an InputStream from a URL, so we can download the data from it.
InputStream inputStream = new BufferedInputStream(url.openStream());

//Create an OutputStream so we can write the data we get from URL to the file
OutputStream outputStream = new FileOutputStream("/sdcard/myfile.jpg");

//create a temporary buffer to store the bytes we get from the URL
byte Data[] = new byte[1024];

long total = 0; //-< you don't actually use this anywhere..

//here, you read your InputStream (URL), into your temporary buffer, and you                                                
//also increment the count variable based on the number of bytes read.
//If there is no more data (read(...) returns -1) exit the loop, as we are finished.
while ((count=inputStream.read(Data)) != -1) {

    total = total+count;  //this is not actually used.. Also, where did you define "count" ?

    //write the content of the byte array "buffer" to the outputStream.
    //the "count" variable tells the outputStream how much you want to write.
    outputStream.write(Data,0,count);

   //After, do the whole thing again.
}

有趣的是循环控制语句:

while ((count=inputStream.read(Data)) != -1)

这里发生的是循环控制语句内的赋值。这与此等效,只是更短:

count = inputStream.read(Data);
while(count != -1) {

 ...do something

 count = inputStream.read(Data);
}

这里的另一件事是 inputStream.read(Data) 。这会将字节读取到临时缓冲区 ( Data ),并且它返回读取的字节数,或 -1如果没有了。这使我们能够以简单的方式传输数据,就像这里一样,通过检查 read(...) 的返回值。控制数据的写入方式并在没有剩余数据时停止。

<小时/>

请注意,您应该始终关闭您的InputStreamOutputStream当不再需要它时,否则您可能会得到损坏或不完整的文件。您可以使用 .close() 来执行此操作方法。

关于java - java中用字节写入文件的概念是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29880515/

相关文章:

java - 反恶意软件服务可执行文件减慢 IO 操作

java - Spring Web 应用程序中意外的结果集已关闭异常

android - 删除目录中最旧的文件,直到它小于特定文件大小

java - removeEldestEntry 覆盖

java - 如何比较两个文本文件的内容并输出到另一个文本文件中?文本1 - 文本2

java - 如何使用剪辑来减少绘画时间?

file - 在 node.js 中获取上传的文件名/路径

java - 使用特定应用程序 java 打开 mp3 文件

java - 如何使用 FileOutputStream 写入数据而不丢失旧数据?

java - 使用 collections.reverseOrder() 反转自然顺序