java_croe 学习笔记之新IO---java.nio 之内存映射文件

发布日期: 2009-8-25 23:37:54 作者:  摘自来源: JavaEye博客 

http://12616383.javaeye.com/blog/457582

 

参考:

无格式输入流 110秒

缓冲输入流     9.9秒

随机存取文件  162秒

内存映射文件   7.2秒

 

例子

Java代码 复制代码
  1. package twelve;   
  2.   
  3. import java.io.BufferedInputStream;   
  4. import java.io.FileInputStream;   
  5. import java.io.FileNotFoundException;   
  6. import java.io.IOException;   
  7. import java.io.InputStream;   
  8. import java.io.RandomAccessFile;   
  9. import java.nio.MappedByteBuffer;   
  10. import java.nio.channels.FileChannel;   
  11. import java.util.zip.CRC32;   
  12.   
  13. /**  
  14.   @Title NIOTTest.java  
  15.   @description  TODO  
  16.   @author qinpeng  
  17.   @date Aug 25, 2009 10:23:26 PM  
  18.  */  
  19. public class NIOTTest {   
  20.        
  21.     public static void main(String[] args) {   
  22.            
  23.         String fileName = "d://IOTest.pdf";   
  24.            
  25.         System.out.println("inputStream");   
  26.         long start = System.currentTimeMillis();   
  27.         long crcValue = checksumInputStreanm(fileName);   
  28.         long end = System.currentTimeMillis();   
  29.         System.out.println(Long.toHexString(crcValue));   
  30.         System.out.println((end - start)+"耗时");   
  31.            
  32.         System.out.println("BufferedinputStream");   
  33.         start = System.currentTimeMillis();   
  34.         crcValue = checksumInputStreanm(fileName);   
  35.         end = System.currentTimeMillis();   
  36.         System.out.println(Long.toHexString(crcValue));   
  37.         System.out.println((end - start)+"耗时");   
  38.            
  39.         System.out.println("RandomAccessFileinputStream");   
  40.         start = System.currentTimeMillis();   
  41.         crcValue = checksumInputStreanm(fileName);   
  42.         end = System.currentTimeMillis();   
  43.         System.out.println(Long.toHexString(crcValue));   
  44.         System.out.println((end - start)+"耗时");   
  45.            
  46.         System.out.println(" MappedFile inputStream");   
  47.         start = System.currentTimeMillis();   
  48.         crcValue = checksumInputStreanm(fileName);   
  49.         end = System.currentTimeMillis();   
  50.         System.out.println(Long.toHexString(crcValue));   
  51.         System.out.println((end - start)+"耗时");   
  52.     }   
  53.        
  54.        
  55.        
  56.     public static long checksumInputStreanm(String fileName){   
  57.         CRC32 crc = new CRC32();   
  58.         try {   
  59.             InputStream in = new FileInputStream(fileName);   
  60.             int c;   
  61.             while((c=in.read())!=-1){   
  62.                 crc.update(c);   
  63.             }   
  64.         } catch (FileNotFoundException e) {   
  65.             e.printStackTrace();   
  66.             System.err.print("NIOTTest--checksumInputStreanm--new FileInputStream is not found");   
  67.         } catch(IOException ioe){   
  68.             ioe.printStackTrace();   
  69.             System.err.print("NIOTTest--checksumInputStreanm--new FileInputStream'read append IOException");   
  70.         }   
  71.         return crc.getValue();   
  72.     }   
  73.        
  74.     public static long checksumBufferedInputStream(String fileName){   
  75.         CRC32 crc = new CRC32();   
  76.         try {   
  77.             InputStream in = new BufferedInputStream(new FileInputStream(fileName));   
  78.             int c;   
  79.             while((c=in.read())!=-1){   
  80.                 crc.update(c);   
  81.             }   
  82.         } catch (FileNotFoundException e) {   
  83.             e.printStackTrace();   
  84.             System.err.print("NIOTTest--checksumBufferedInputStream--new FileInputStream is not found");   
  85.         } catch(IOException ioe){   
  86.             ioe.printStackTrace();   
  87.             System.err.print("NIOTTest--checksumBufferedInputStream--new FileInputStream'read append IOException");   
  88.         }   
  89.         return crc.getValue();   
  90.     }   
  91.        
  92.        
  93.     public static long checksumRondomAccessFileInputStream(String fileName){   
  94.         CRC32 crc = new CRC32();   
  95.         try {   
  96.             RandomAccessFile file = new RandomAccessFile(fileName,"r");   
  97.             int c;   
  98.             while((c=file.read())!=-1){   
  99.                 crc.update(c);   
  100.             }   
  101.         } catch (FileNotFoundException e) {   
  102.             e.printStackTrace();   
  103.             System.err.print("NIOTTest--checksumRondomAccessFileInputStream--new FileInputStream is not found");   
  104.         } catch(IOException ioe){   
  105.             ioe.printStackTrace();   
  106.             System.err.print("NIOTTest--checksumRondomAccessFileInputStream--new FileInputStream'read append IOException");   
  107.         }   
  108.         return crc.getValue();   
  109.     }   
  110.   
  111.     public static long checksumMappedFile(String fileName){   
  112.         CRC32 crc = new CRC32();   
  113.         try {   
  114.             FileInputStream in = new FileInputStream(fileName);   
  115.             FileChannel channel = in.getChannel();   
  116.             int length = (int) channel.size();   
  117.             MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);   
  118.                
  119.             for(int p = 0;p<length;p++){   
  120.                 int c = buffer.getInt(p);   
  121.                 crc.update(c);   
  122.             }   
  123.         } catch (FileNotFoundException e) {   
  124.             e.printStackTrace();   
  125.             System.err.print("NIOTTest--checksumRondomAccessFileInputStream--new FileInputStream is not found");   
  126.         } catch(IOException ioe){   
  127.             ioe.printStackTrace();   
  128.             System.err.print("NIOTTest--checksumRondomAccessFileInputStream--new FileInputStream'read append IOException");   
  129.         }   
  130.         return crc.getValue();   
  131.     }   
  132.        
  133.        
  134. }  

------------------------------------------------】

有了内存映射文件,你就可以认为文件已经全部读进了内存,然后把它当成一个非常大的数组来访问了。这种解决思路能大大简化修改文件的代码。下面就是一个简单的例子:

代码
import java.io.*;  
import java.nio.*;  
import java.nio.channels.*;  
public class LargeMappedFiles {  
  static int length = 0x8FFFFFF; // 128 Mb  
  public static void main(String[] args) throws Exception {  
    MappedByteBuffer out =   
      new RandomAccessFile("test.dat", "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length);  
    for(int i = 0; i < length; i++)  
      out.put((byte)'x');  
    System.out.println("Finished writing");  
    for(int i = length/2; i < length/2 + 6; i++)  
      System.out.print((char)out.get(i));  
  }  
}  
    为了能以读写的方式打开文件,我们从RandomAccessFile入手。

    拿到channel之后,我们用map( )方法生成了一个MappedByteBuffer。这是一种特殊的"direct buffer"。注意,你必须指明,它是从文件的哪个位置开始映射的,映射的范围又有多大;也就是说,它还可以映射一个大文件的某个小片断。

   MappedByteBuffer是ByteBuffer的派生类,因此它具备了ByteBuffer的所有方法。这里只简单地演示了一下put( )和get( )方法,除此之外,你还可以使用asCharBuffer( )之类的方法。
    上述例程创建了一个128MB的文件,或许这已经超出OS的允许范围了。文件的访问好像只是一瞬间的事,这是因为,真正调入内存的只是其中的一小部分,其余部分则被放在交换文件上。这样你就可以很方便地修改超大型的文件了(最大可以到2 GB)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值