JAVA NIO学习

      貌似很久以前最初学习Java的时候顺带过学习了下NIO方面的,现在再看NIO根本不知道是什么东西了,这忘的,都不好意思说知道NIO了,虽然貌似说现在io.*里很多都有类似NIO的实现部分,不过去年做数据处理时还是发现阻塞式力不从心,目测以后会用到NIO的地方也会较多,提前复习+学习下,随便记录下代码做一记录,有时间的话再写写学习笔记好了。

	/**
	 * 基本的写
	 * @param filePath 文件路径
	 */
	public void write(String filePath) {
		FileOutputStream fout = null;
		try {
			String str = "NIO WRITE Test";
			byte[] message = str.getBytes();
			fout = new FileOutputStream(filePath);
			FileChannel fc = fout.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			for (int i = 0; i < message.length; i++) {
				buffer.put(message[i]);
			}
			buffer.flip();
			fc.write(buffer);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fout.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 基本的读
	 * @param filePath 文件路径
	 */
	public void read(String filePath){
		FileInputStream fin = null;
		try {
			fin = new FileInputStream(filePath);
			FileChannel fc = fin.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			fc.read(buffer);
			byte[] b = buffer.array();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 文件拷贝
	 * @param from 源文件路径
	 * @param to 目标文件路径
	 */
	public void copy(String from,String to){
		FileInputStream fin = null;
		FileOutputStream fout = null;
		try {
			fin = new FileInputStream(from);
			fout = new FileOutputStream(to);
			FileChannel finChannel = fin.getChannel();
			FileChannel foutChannel = fout.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			while(finChannel.read(buffer) != -1){
				buffer.flip();
				foutChannel.write(buffer);
				buffer.clear();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
其中flip()的使用和读写模式及Buffer的Capacity,Position,Limit有关,先Mark下。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值