Java 内存映射文件MappedByteBuffer
生活随笔
收集整理的這篇文章主要介紹了
Java 内存映射文件MappedByteBuffer
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
MappedByteBuffer是java nio引入的文件內存映射方案,讀寫性能極高。在NIO中主要用到普通的輸入流,帶緩沖的輸入流,RandomAccessFile和MappedByteBuffer。
現在我們來看看這四種流的效率,廢話少說直接上代碼。
我們采用CRC32來循環冗余校驗。CRC32在java.util.zip包中。
1.普通的輸入流。
public static long checksumInputStream(Path filename) throws IOException
{
try (InputStream in = Files.newInputStream(filename))
{
CRC32 crc = new CRC32();
int c;
while ((c = in.read()) != -1)
crc.update(c);
return crc.getValue();
}
}
2.帶緩沖的輸入流
public static long checksumBufferedInputStream(Path filename) throws IOException
{
try (InputStream in = new BufferedInputStream(Files.newInputStream(filename)))
{
CRC32 crc = new CRC32();
int c;
while ((c = in.read()) != -1)
crc.update(c);
return crc.getValue();
}
}
3.RandomAccessFile
public static long checksumRandomAccessFile(Path filename) throws IOException
{
try (RandomAccessFile file = new RandomAccessFile(filename.toFile(), "r"))
{
long length = file.length();
CRC32 crc = new CRC32();
for (long p = 0; p < length; p++)
{
file.seek(p);
int c = file.readByte();
crc.update(c);
}
return crc.getValue();
}
}
4.MappedByteBuffer
public static long checksumMappedFile(Path filename) throws IOException
{
try (FileChannel channel = FileChannel.open(filename))
{
CRC32 crc = new CRC32();
int length = (int) channel.size();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
for (int p = 0; p < length; p++)
{
int c = buffer.get(p);
crc.update(c);
}
return crc.getValue();
}
}
每個流對應的方法寫好之后我們來開始測試
public static void main(String[] args) throws IOException {
String name = "txt.txt";
Path filename = Paths.get(name);
long start, crcValue, end;
System.out.println("Input Stream:");
start = System.currentTimeMillis();
crcValue = checksumInputStream(filename);
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end - start) + " milliseconds");
System.out.println("Buffered Input Stream:");
start = System.currentTimeMillis();
crcValue = checksumBufferedInputStream(filename);
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end - start) + " milliseconds");
System.out.println("Random Access File:");
start = System.currentTimeMillis();
crcValue = checksumRandomAccessFile(filename);
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end - start) + " milliseconds");
System.out.println("Mapped File:");
start = System.currentTimeMillis();
crcValue = checksumMappedFile(filename);
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end - start) + " milliseconds");
}
為了保證每種流相互之間對結果沒有影響,我們可以分別把main方法中其他流的代碼注釋掉。
最后可以看到MappedByteBuffer效率最高,所消耗的時間最少。
總結
以上是生活随笔為你收集整理的Java 内存映射文件MappedByteBuffer的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是美篇
- 下一篇: 郑好办app查询房产信息流程