package cn.luxh.app; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import org.junit.Test; public class NioTester { /** * 读取文件 * 获取通道;创建缓冲区;让通道将数据读到这个缓冲区中。 */ @Test public void testRead() { FileInputStream fis = null; FileChannel channel = null; try { //获取通道Channel,从FileInputStream中获取 fis = new FileInputStream("D:/test.rar"); channel = fis.getChannel(); //创建缓冲区 ByteBuffer buffer = ByteBuffer.allocate(1024); //将数据从通道读取到缓冲区 channel.read(buffer); //业务处理 //... } catch (IOException e) { e.printStackTrace(); }finally { try { if(fis != null) { fis.close(); } if(channel != null) { channel.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 写文件 * 获取通道;创建一个缓冲区,用数据填充它;然后让通道用这些数据来执行写入操作。 */ @Test public void testWrite() { FileOutputStream fos = null; FileChannel channel = null; try { //获取通道,从FileOutputStream获取 fos = new FileOutputStream("D:/test.txt"); channel = fos.getChannel(); //创建缓冲区 ByteBuffer buffer = ByteBuffer.allocate(1024); String words = "hey,girl.I am a coder."; byte[] message = words.getBytes(Charset.defaultCharset()); buffer.put(message); buffer.flip(); channel.write(buffer); }catch(IOException e) { e.printStackTrace(); }finally { try { if(fos != null) { fos.close(); } if(channel != null) { channel.close(); } }catch(IOException e){ e.printStackTrace(); } } } /** * 读写操作 * 获取通道;创建一个 Buffer,然后从源文件中将数据读到这个缓冲区中; * 然后将缓冲区写入目标文件。 * 不断重复 读写 直到源文件结束。 */ @Test public void testReadAndWrite() { FileInputStream fis = null; FileChannel inChannel = null; FileOutputStream fos = null; FileChannel outChannel = null; try { fis = new FileInputStream("D:/test.txt"); inChannel = fis.getChannel(); fos = new FileOutputStream("D:/test2.txt"); outChannel = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while(true) { //重设缓冲区,使它可以接受读入的数据。 buffer.clear(); if(inChannel.read(buffer)==-1) { break; } //让缓冲区可以将新读入的数据写入通道 buffer.flip(); outChannel.write(buffer); } }catch(Exception e) { e.printStackTrace(); }finally { try { if(fos != null) { fos.close(); } if(outChannel != null) { outChannel.close(); } if(fis != null) { fis.close(); } if(inChannel != null) { inChannel.close(); } }catch(IOException e){ e.printStackTrace(); } } } }