0

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

我在Java编程领域缺乏很多知识,所以如果我问错了问题,请原谅我。:秒

4

3 回答 3

2

缓冲区是内存中的一个空间,在处理数据之前临时存储数据。见维基文章

下面是一个简单的Java 示例,说明如何使用 ByteBuffer 类。

更新

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();     
}

希望能把事情弄清楚一点。

于 2009-08-28T10:54:13.780 回答
1

对于缓冲区,人们通常指的是一些内存块来临时存储一些数据。缓冲区的一个主要用途是 I/O 操作。

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

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

于 2009-08-28T10:53:20.910 回答
0

关于 I/O 的 Sun Java 教程部分涵盖了这个主题:

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

于 2009-08-28T10:53:50.317 回答