在java中使用字节写文件的概念是什么?

时间:2015-04-26 16:49:00

标签: 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?

有谁能形容我这是怎么发生的?感谢

3 个答案:

答案 0 :(得分:8)

这段代码的作用是将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()方法执行此操作。

答案 1 :(得分:3)

  

请注意我只想要写文件的概念。这段代码是示例而不是真正完整的代码

让我们从检查非缓冲IO开始。

try (InputStream inputStream = new BufferedInputStream(url.openStream());
    OutputStream outputStream = new FileOutputStream("/sdcard/myfile.jpg")) {
    int b;
    while ((b = inputStream.read()) != -1) {
        outputStream.write(b);
    }
}

这将一次读写一个字节。大多数物理设备支持缓冲(一种或另一种形式)。它们实际上可以一次读取多个字节(或传输多个字节的数据包)。在这种情况下,使用缓冲区读取效率更高(记住close块中的finally或使用try-with-resources Statement

<强> TL;博士

非缓冲IO一次读取一个字节(一兆字节,即一百万次读取调用)。缓冲IO读取多个字节作为以优化或减少read(s)。

答案 2 :(得分:-4)

该代码会从您的URL下载文件并将其保存为/sdcard/myfile.jpg,如果这就是您所要求的。