Java nio(三)
一、读文件:
前面我们介绍了通过获得FileChannel来写文件,现在我们再看看读操作。
其实读操作和写操作基本是对应的。
首先与写操作类似从文件中获得流,读操作要获得输入流FileInputStream
,再从这个流中得到FileChannel对象,然后进行读操作。
文件通道的读操作有三个read()方法:
int read(ByteBuffer buf);从文件中读取buf.remaining()[即limit-position]个字节到缓冲区buf,从缓冲区的当前位置开始存取int read(ByteBuffer[] buffers);从文件中读到多个缓冲区中int read(ByteBuffer[] buffers,int offset,int length);从文件中读到buffers[offset]--buffers[offset+length-1]缓冲区中
File file = new File("D:\text.txt");FileInputStream fis = new FileInputStream(file);FileChannel inputChannel = fis.getChannel();ByteBuffer buf = ByteBuffer.allocate(48);while(inChannel.read(buf) != -1){ //....从buf中提取出数据;for example: System.out.println(buf.filp().asCharBuffer().toString()); buf.clear();}
File fromFile = new File("D:/from.txt"); File toFile = new File("D:/to.txt"); FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel(); int byteWritten = 0; long byteCount = inChannel.size(); while(byteWritten < byteCount){ byteWritten += inChannel.transferTo(bytesWritten,byteCount- bytesWritten,outChannel); } fis.close(); fos.close();
File file = new File("D:\test.txt");RandomAccessFile raf = new RandomAccessFile(file,"rw");FileChannel ioChannel = rad.getChannel();
File file = new File("D:\test.txt");RandomAccessFile raf = new RandomAccessFile(file,"rw");FileChannel ioChannel = rad.getChannel();MappedByteBuffer buf = ioChannel.map(READ_WRITE.0L,ioChannel.size()).load();
public static void testReadPrimitiveBuffer()throws Exception{ int i; long l; double d; char ch; ByteBuffer buffer = ByteBuffer.allocate(100); FileInputStream fis = new FileInputStream(new File("D:/primitive.txt")); FileChannel inputChannel = fis.getChannel(); inputChannel.read(buffer); buffer.flip(); i = buffer.getInt(); l = buffer.getLong(); d = buffer.getDouble(); ch = buffer.getChar(); System.out.println("i=" + i + ",l=" + l + ",d=" + d + ",ch=" + ch); }2 楼 bojianpc 2008-09-08 不错哦最近项目要用 可以向你请教此类的问题么 我的QQ1067302 希望能得到你的恢复