我知道当我想写一个文件时,我应该使用这样的代码:
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(...)
的返回值。控制数据的写入方式并在没有剩余数据时停止。
请注意,您应该始终关闭您的InputStream
和OutputStream
当不再需要它时,否则您可能会得到损坏或不完整的文件。您可以使用 .close()
来执行此操作方法。
关于java - java中用字节写入文件的概念是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29880515/