码迷,mamicode.com
首页 > 其他好文 > 详细

利用FileChannel完成文件的读、写、复制

时间:2015-05-05 14:26:08      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

内容:通过NIO中的FileChannel完成文件的读、写、复制。

public class NioFileCopy {
	private RandomAccessFile aFile = null;
	private FileChannel inChannel = null;
	private final ByteBuffer buf = ByteBuffer.allocate(1024);
	
	public void doWrite() throws IOException {
		aFile = new RandomAccessFile("C:/goods.txt", "rw");
		inChannel = aFile.getChannel();
		String newData = "New String to wirte to file... " + System.currentTimeMillis();
		buf.clear();
		buf.put(newData.getBytes());
		
		buf.flip();
		
		while (buf.hasRemaining()) 
			inChannel.write(buf);
		
		inChannel.close();
		System.out.println("Write Over");
	}
	
	public void doRead() throws IOException {
		aFile = new RandomAccessFile("C:/goods.txt", "rw");
		inChannel = aFile.getChannel();
		
		int bytesRead = inChannel.read(buf);
		while (bytesRead != -1) {
			System.out.println("Read " + bytesRead);
			buf.flip();
			while (buf.hasRemaining())
				System.out.print((char) buf.get());
			
			buf.clear();
			bytesRead = inChannel.read(buf);
		}
		
		aFile.close();
	}
	
	public void doCopy() throws IOException {
		aFile = new RandomAccessFile("C:/goods.txt", "rw");
		inChannel = aFile.getChannel();
		RandomAccessFile bFile = new RandomAccessFile("C:/22.log", "rw");
		FileChannel outChannel = bFile.getChannel();
		inChannel.transferTo(0, inChannel.size(), outChannel);
		System.out.println("Copy over");
	}
	
	public static void main(String[] args) throws IOException {
		NioFileCopy tool = new NioFileCopy();
		//tool.doWrite();
		//tool.doRead();
		tool.doCopy();
	}
}


利用FileChannel完成文件的读、写、复制

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45501559

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!