缓冲区和字节?
问题描述:
有人可以向我解释使用缓冲区的用法,也可能是一些简单的(记录在案的)正在使用的缓冲区的例子。谢谢。缓冲区和字节?
我在Java编程的这个领域缺乏太多的知识,所以请原谅我,如果我问错了问题。 :s
答
缓冲区是在那里它被处理之前的数据临时存储在内存中的空间。请参阅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();
}
希望扫清事情了一点。
答
对于缓冲区,人们通常意味着要临时存储一些数据的一些内存块。缓冲区的一个主要用途是在I/O操作中。
像硬盘这样的设备擅长快速读取或写入磁盘上的连续位块。如果您告诉硬盘“读取这10,000个字节并将其放入内存中”,则可以非常快速地读取大量数据。如果你要编程一个循环并逐个获取字节,告诉硬盘每次获得一个字节,这将是非常低效和缓慢的。
因此,您创建一个10,000字节的缓冲区,告诉硬盘一次读取所有字节,然后从内存缓冲区中逐个处理这些10,000字节。
我认为你需要更具体。到目前为止,这似乎并不特定于Java - 除非您指的是java.nio.ByteBuffer?你有什么特别的想法,你遇到了什么问题? – 2009-08-28 10:56:31