【问题标题】:Buffers and bytes?缓冲区和字节?
【发布时间】:2009-08-28 10:47:35
【问题描述】:

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

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

【问题讨论】:

  • 我认为您需要更具体一些。到目前为止,这似乎并不是 Java 特有的——除非您指的是 java.nio.ByteBuffer?您具体想做什么,遇到了什么问题?

标签: java buffer byte


【解决方案1】:

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

这里有一个简单的Java example 说明如何使用 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();     
}

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

【讨论】:

  • 也许您可以复制那段简单的代码并记录每一行?
  • 感谢记录,真的有帮助!
  • +1 用于记录这段丑陋的代码。看看那个 for- 循环!异常处理(不保证通道关闭后)!我以它为例来教我的团队交付干净的代码。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      • 2021-08-29
      相关资源
      最近更新 更多