CN.programmer.Luxh博客园

nio简单读写Posted on

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 {/*** 读取文件* 获取通道;创建缓冲区;让通道将数据读到这个缓冲区中。*/@Testpublic 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();}}}/*** 写文件* 获取通道;创建一个缓冲区,香港服务器租用,香港虚拟主机,用数据填充它;然后让通道用这些数据来执行写入操作。*/@Testpublic 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,然后从源文件中将数据读到这个缓冲区中;* 然后将缓冲区写入目标文件。* 不断重复 读写 直到源文件结束。*/@Testpublic 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();}}}}

,香港空间你曾经说,你曾经说。走在爱的旅途,我们的脚步多么轻松……

CN.programmer.Luxh博客园

相关文章:

你感兴趣的文章:

标签云: