Java NIO读,写,拷贝文件

private static void readNIO() {
		try {

			// 第一步:获取通道
			FileInputStream fis1 = new FileInputStream("Maven_IP.txt");
			// FileChannel:从文件读取数据的
			FileChannel channel = fis1.getChannel();

			// 第二步:创建缓冲区
			ByteBuffer bb = ByteBuffer.allocate(1024);

			// 第三步:将数据从通道读到缓冲区
			int count = channel.read(bb);

			// java.nio.HeapByteBuffer[pos=151 lim=1024 cap=1024]
			// 将position是位置:limit:上限; capacity:容量;
			System.out.println(bb);

			// java.nio.HeapByteBuffer[pos=0 lim=151 cap=1024]
			//重设一下position=0
			bb.flip();
			//
			System.out.println(bb);
			// 剩余的字节数 remaining(limit - position);=151-0>0
			while (bb.remaining() > 0) {
				// 获得字节!
				System.out.print((char) bb.get());

			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



写文件:

private static void writeNIO() {
		try {

			// 第一步:获取通道
			FileOutputStream fos = new FileOutputStream("my.txt");
			// FileChannel:从文件读取数据的
			FileChannel channel = fos.getChannel();

			// 第二步:创建缓冲区
			ByteBuffer buffer = ByteBuffer.allocate(1024);

			// 第二步:将数据放入缓冲区
			String[] strings = { "a", "b", "c", "f" };
			for (int i = 0; i < strings.length; i++) {
				buffer.put(strings[i].getBytes());
			}
//			重设一下postion=0
			buffer.flip();

			// 第三步:把缓冲区数据写入通道中
			channel.write(buffer);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



拷贝文件

public static void copyFileUseNIO(String src, String dst)
			throws IOException {
		// 声明源文件和目标文件
		FileInputStream fi = new FileInputStream(new File(src));
		FileOutputStream fo = new FileOutputStream(new File(dst));
		// 获得传输通道channel
		FileChannel inChannel = fi.getChannel();
		FileChannel outChannel = fo.getChannel();
		// 获得容器buffer
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while (true) {
			// 判断是否读完文件
			int eof = inChannel.read(buffer);
			if (eof == -1) {
				break;
			}
			// 重设一下buffer的position=0,limit=position
			buffer.flip();
			// 开始写
			outChannel.write(buffer);
			// 写完要重置buffer,重设position=0,limit=capacity
			buffer.clear();
		}
		inChannel.close();
		outChannel.close();
		fi.close();
		fo.close();
	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值