转载《Java编程思想》Java I/O系统章节阅读笔记

来源:互联网 发布:如何恢复手机sd卡数据 编辑:程序博客网 时间:2024/04/26 15:38

      今天正好要写个小程序需要用到io操作,突然想起来java有个nio一直没用过,就找了点资料研究了一下,顺便做点笔记,以便日后查阅。

-------------------------------------------------------------------------------------------------------------------------------------------

编程语言的I/O类库中常使用流的概念,但它屏蔽了实际的I/O设备中处理数据的细节。在Java中很少使用单一的类来创建流对象,而是通过叠合多个对象来提供所期望的功能(用到了装饰器模式)。InputStream和OutputStream就是用来输入和输出的。在Java1.1中,Reader和Writer利用适配器转换了它们来实现国际化,因为老的I/O流继承结果仅支持8位字节流,不能很好的处理16位的Unicode字符。

文件操作的类:FileInputReader,FileOutputReader,RandomAccessFile。其中RandomAccessFile是一个自我独立的类,虽然可读可写,但都是自己内部实现,并没继承输入输出流的层次结构。在JDK1.4中,其大部分功能已经由nio内存映射文件所取代。

基本的文件输出:FileWriter对象可以向文件写入数据,实际上,我们通常会用BufferedWriter将其包装起来用以缓冲输出,为了提供格式化机制,它又被装饰成PrintWriter。例如:new PrintWriter(new BufferedWriter(new FileWriter(file))),在J2SE 5中甲了一个辅助构造器,可以简写成new PrintWriter(file)。

管道流:PipedInputStream,PipedOutputStream,PipedReader及PipedWriter,它们的价值在多线程中才能体现,因为管道流用于任务之间的通信。

-------------------------------------------------------------------------------------------------------------------------------------------

new I/O:目的是为了提高速度,在新版本的JDK中,旧的I/O也使用nio重新实现,有性能提升。速度的提高来自于所使用的结构更接近于操作系统的执行I/O方式——通道和缓冲器。

流使用getChannel()方法会产生一个FileChannel。通道是一种相当基础的东西:可以向它传送用于读写的ByteBuffer,并且可以锁定文件的某些区域用于独占式访问(后面有提到)。

  1. import java.nio.*;  
  2. import java.nio.channels.*;  
  3. import java.io.*;  
  4.  
  5. public class GetChannel {  
  6.   private static final int BSIZE = 1024;  
  7.   public static void main(String[] args) throws Exception {  
  8.     // Write a file:  
  9.     FileChannel fc =  
  10.       new FileOutputStream("data.txt").getChannel();  
  11.     fc.write(ByteBuffer.wrap("Some text ".getBytes()));  
  12.     fc.close();  
  13.     // Add to the end of the file:  
  14.     fc = new RandomAccessFile("data.txt""rw").getChannel();  
  15.     fc.position(fc.size()); // Move to the end  
  16.     fc.write(ByteBuffer.wrap("Some more".getBytes()));  
  17.     fc.close();  
  18.     // Read the file:  
  19.     fc = new FileInputStream("data.txt").getChannel();  
  20.     ByteBuffer buff = ByteBuffer.allocate(BSIZE);  
  21.     fc.read(buff);  
  22.     buff.flip();  
  23.     while(buff.hasRemaining())  
  24.       System.out.print((char)buff.get());  
  25.   }  
  26. }  
  27.  

将字节存放于ByteBuffer有2种方法:一是用put方法直接填充一个或多个字节,或基本数据类型;另一种是用warp方法将已存在的字节数组包装到ByteBuffer中。对于只读访问,我们必须显示的使用静态的allocate方法分配ByteBuffer。nio的目标就是快速移动大量数据,因此ByteBuffer的大小就很重要——需要在实际运行的程序中测试来找到最佳值。要达到更高的速度也有可能,方法就是使用allocateDirect()而不是allocate(),以产生一个与操作系统有更高耦合性的“直接”缓冲器,但效果需要实际测试一下。

  1. import java.nio.*;  
  2. import java.nio.channels.*;  
  3. import java.io.*;  
  4.  
  5. public class ChannelCopy {  
  6.   private static final int BSIZE = 1024;  
  7.   public static void main(String[] args) throws Exception {  
  8.     if(args.length != 2) {  
  9.       System.out.println("arguments: sourcefile destfile");  
  10.       System.exit(1);  
  11.     }  
  12.     FileChannel in = new FileInputStream(args[0]).getChannel();  
  13.     FileChannel out = new FileOutputStream(args[1]).getChannel();  
  14.     //有一种特殊的办法,将2个通道直接相连   
  15.     // in = transferTo(0, in.size(), out); 或者 out = transferFrom(in, 0, in.size());  
  16.     ByteBuffer buffer = ByteBuffer.allocate(BSIZE);  
  17.     while(in.read(buffer) != -1) {  
  18.       buffer.flip(); // Prepare for writing  
  19.       out.write(buffer);  
  20.       buffer.clear();  // Prepare for reading  
  21.     }  
  22.   }  
  23. }  

BufferWriter转换成char型来操作,很不方便,我们利用CharBuffer的toString()方法来转换成String型就方便多了。

  1. import java.nio.*;  
  2. import java.nio.channels.*;  
  3. import java.nio.charset.*;  
  4. import java.io.*;  
  5.  
  6. public class BufferToText {  
  7.   private static final int BSIZE = 1024;  
  8.   public static void main(String[] args) throws Exception {  
  9.     FileChannel fc =  
  10.       new FileOutputStream("data2.txt").getChannel();  
  11.     fc.write(ByteBuffer.wrap("Some text".getBytes()));  
  12.     fc.close();  
  13.     fc = new FileInputStream("data2.txt").getChannel();  
  14.     ByteBuffer buff = ByteBuffer.allocate(BSIZE);  
  15.     fc.read(buff);  
  16.     buff.flip();  
  17.     // Doesn't work:  
  18.     System.out.println(buff.asCharBuffer());  
  19.     // Decode using this system's default Charset:  
  20.     buff.rewind();  
  21.     String encoding = System.getProperty("file.encoding");  
  22.     System.out.println("Decoded using " + encoding + ": " 
  23.       + Charset.forName(encoding).decode(buff));  
  24.     // Or, we could encode with something that will print:  
  25.     fc = new FileOutputStream("data2.txt").getChannel();  
  26.     fc.write(ByteBuffer.wrap(  
  27.       "Some text".getBytes("UTF-16BE")));  
  28.     fc.close();  
  29.     // Now try reading again:  
  30.     fc = new FileInputStream("data2.txt").getChannel();  
  31.     buff.clear();  
  32.     fc.read(buff);  
  33.     buff.flip();  
  34.     System.out.println(buff.asCharBuffer());  
  35.     // Use a CharBuffer to write through:  
  36.     fc = new FileOutputStream("data2.txt").getChannel();  
  37.     buff = ByteBuffer.allocate(24); // More than needed  
  38.     buff.asCharBuffer().put("Some text");  
  39.     fc.write(buff);  
  40.     fc.close();  
  41.     // Read and display:  
  42.     fc = new FileInputStream("data2.txt").getChannel();  
  43.     buff.clear();  
  44.     fc.read(buff);  
  45.     buff.flip();  
  46.     System.out.println(buff.asCharBuffer());  
  47.   }  
  48. }  
  49.  

-------------------------------------------------------------------------------------------------------------------------------------------

内存映射文件:它允许我们创建和修改那些因为太大而不能放入内存的文件。

  1. import java.nio.*;  
  2. import java.nio.channels.*;  
  3. import java.io.*;  
  4. import static net.mindview.util.Print.*;  
  5.  
  6. public class LargeMappedFiles {  
  7.   static int length = 0x8FFFFFF// 128 MB  
  8.   public static void main(String[] args) throws Exception {  
  9.     MappedByteBuffer out =  
  10.       new RandomAccessFile("test.dat""rw").getChannel()  
  11.       .map(FileChannel.MapMode.READ_WRITE, 0, length);  
  12.     for(int i = 0; i < length; i++)  
  13.       out.put((byte)'x');  
  14.     print("Finished writing");  
  15.     for(int i = length/2; i < length/2 + 6; i++)  
  16.       printnb((char)out.get(i));  
  17.   }  
  18. }  
  19.  

文件加锁:通过对FileChannel调用tryLock()和lock(),就可以获得整个文件的FileLock。启动tryLock()是非阻塞式的,它设法获取锁,但如果不能获得,将直接放方法调用返回。lock()是阻塞式的,它要阻塞线程直到获得锁,或者调用lock()的线程中断,或者调用lock()的通道关闭。

  1. import java.nio.channels.*;  
  2. import java.util.concurrent.*;  
  3. import java.io.*;  
  4.  
  5. public class FileLocking {  
  6.   public static void main(String[] args) throws Exception {  
  7.     FileOutputStream fos= new FileOutputStream("file.txt");  
  8.     FileLock fl = fos.getChannel().tryLock();  
  9.     if(fl != null) {  
  10.       System.out.println("Locked File");  
  11.       TimeUnit.MILLISECONDS.sleep(100);  
  12.       fl.release();  
  13.       System.out.println("Released Lock");  
  14.     }  
  15.     fos.close();  
  16.   }  
  17. }  
  18.  

对映射文件的部分加锁:

  1. import java.nio.*;  
  2. import java.nio.channels.*;  
  3. import java.io.*;  
  4.  
  5. public class LockingMappedFiles {  
  6.   static final int LENGTH = 0x8FFFFFF// 128 MB  
  7.   static FileChannel fc;  
  8.   public static void main(String[] args) throws Exception {  
  9.     fc =  
  10.       new RandomAccessFile("test.dat""rw").getChannel();  
  11.     MappedByteBuffer out =  
  12.       fc.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);  
  13.     for(int i = 0; i < LENGTH; i++)  
  14.       out.put((byte)'x');  
  15.     new LockAndModify(out, 00 + LENGTH/3);  
  16.     new LockAndModify(out, LENGTH/2, LENGTH/2 + LENGTH/4);  
  17.   }  
  18.   private static class LockAndModify extends Thread {  
  19.     private ByteBuffer buff;  
  20.     private int start, end;  
  21.     LockAndModify(ByteBuffer mbb, int start, int end) {  
  22.       this.start = start;  
  23.       this.end = end;  
  24.       mbb.limit(end);  
  25.       mbb.position(start);  
  26.       buff = mbb.slice();  
  27.       start();  
  28.     }  
  29.     public void run() {  
  30.       try {  
  31.         // Exclusive lock with no overlap:  
  32.         FileLock fl = fc.lock(start, end, false);  
  33.         System.out.println("Locked: "+ start +" to "+ end);  
  34.         // Perform modification:  
  35.         while(buff.position() < buff.limit() - 1)  
  36.           buff.put((byte)(buff.get() + 1));  
  37.         fl.release();  
  38.         System.out.println("Released: "+start+" to "+ end);  
  39.       } catch(IOException e) {  
  40.         throw new RuntimeException(e);  
  41.       }  
  42.     }  
  43.   }  
  44. }