Sad*_*ary 0 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);
}
Run Code Online (Sandbox Code Playgroud)
但我无法理解该结果会发生什么,是否将图像文件从零写入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.
}
Run Code Online (Sandbox Code Playgroud)
有趣的是循环控制语句:
while ((count=inputStream.read(Data)) != -1)
Run Code Online (Sandbox Code Playgroud)
这到底是怎么发生的是分配内循环控制语句.这相当于此,只是更短:
count = inputStream.read(Data);
while(count != -1) {
...do something
count = inputStream.read(Data);
}
Run Code Online (Sandbox Code Playgroud)
这里的另一件事是inputStream.read(Data).这将字节读入临时缓冲区(Data),并且还返回读取的字节数,或者-1如果没有剩余则返回.这允许我们通过检查read(...)控制数据写入方式的返回值以及没有剩余数据时停止来以简单的方式传输数据(如此处).
请注意,您应该始终关闭您的InputStream和OutputStream当不再需要它,因为你可能有一个损坏的或不完整的文件结束,否则.您可以使用该.close()方法执行此操作.