JAVA NIO学习

来源:互联网 发布:c语言源代码实例 编辑:程序博客网 时间:2024/06/05 22:37

      貌似很久以前最初学习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
原创粉丝点击