2009-08-28 236 views
0

有人可以向我解释使用缓冲区的用法,也可能是一些简单的(记录在案的)正在使用的缓冲区的例子。谢谢。缓冲区和字节?

我在Java编程的这个领域缺乏太多的知识,所以请原谅我,如果我问错了问题。 :s

+0

我认为你需要更具体。到目前为止,这似乎并不特定于Java - 除非您指的是java.nio.ByteBuffer?你有什么特别的想法,你遇到了什么问题? – 2009-08-28 10:56:31

回答

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

希望扫清事情了一点。

+0

也许你可以复制那些简单的代码和文档每行? – Rifk 2009-08-28 11:02:21

+0

感谢您的记录,真的有帮助! – Rifk 2009-08-28 11:17:51

+0

+1用于记录这段丑陋的代码。看看那个for循环!异常处理(不保证通道关闭后)!我以此为例来教导我的团队提供干净的代码。 – 2009-08-28 11:55:28

1

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

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

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