缓冲区和字节?

时间:2009-08-28 10:47:35

标签: java buffer byte

有人可以向我解释使用缓冲区的用法,也许还有一些使用缓冲区的简单(记录)示例。感谢。

我对Java编程领域缺乏了解,所以如果我问错了,请原谅我。 :■

3 个答案:

答案 0 :(得分:2)

缓冲区是内存中的一个空间,数据在处理之前会临时存储。见Wiki article

关于如何使用ByteBuffer类的简单Java example

更新

public static void main(String[] args) throws IOException 
{
    // reads in bytes from a file (args[0]) into input stream (inFile)
    FileInputStream inFile = new FileInputStream(args[0]);
    // creates an output stream (outFile) to write bytes to.
    FileOutputStream outFile = new FileOutputStream(args[1]);

    // get the unique channel object of the input file
    FileChannel inChannel = inFile.getChannel();
    // get the unique channel object of the output file.
    FileChannel outChannel = outFile.getChannel();    

    /* create a new byte buffer and pre-allocate 1MB of space in memory
       and continue to read 1mb of data from the file into the buffer until 
       the entire file has been read. */
    for (ByteBuffer buffer = ByteBuffer.allocate(1024*1024); inChannel.read(buffer) !=  1; buffer.clear()) 
    {
       // set the starting position of the buffer to be the current position (1Mb of data in from the last position)
       buffer.flip();
       // write the data from the buffer into the output stream
       while (buffer.hasRemaining()) outChannel.write(buffer);
    }

    // close the file streams.
    inChannel.close();
    outChannel.close();     
}

希望能稍微清理一下。

答案 1 :(得分:1)

使用缓冲区,人们通常意味着一些内存块暂时存储一些数据。缓冲区的一个主要用途是I / O操作。

像硬盘一样的设备可以一次性快速读取或写入磁盘上的连续位块。如果你告诉硬盘“读取这10,000个字节并将它们放在内存中”,那么读取大量数据可以非常快速地完成。如果你要编程一个循环并逐个获取字节,告诉硬盘每次都得到一个字节,那将是非常低效和缓慢的。

因此,您创建一个10,000字节的缓冲区,告诉硬盘一次读取所有字节,然后从内存中的缓冲区逐个处理这10,000个字节。

答案 2 :(得分:0)

有关I / O的Sun Java教程部分介绍了此主题:

http://java.sun.com/docs/books/tutorial/essential/io/index.html

相关问题