使用NIO读写txt文件

java 里面IO是真的烦,平时也不会频繁的去写,参数又多手写根本写不出来,笔试的时候真的是很慌了。

package cn.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFile {

    private static String resource = "E:\\resource.txt";
    private static String destination = "E:\\b.txt";

    public static void main(String[] args) {
        try {
            FileInputStream input = new FileInputStream(resource);
            FileOutputStream out = new FileOutputStream(destination);
            FileChannel readchannel = input.getChannel();
            FileChannel writechannel = out.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while(true) {
                byte[] ds = new byte[1024];
                buffer.clear();
                int len = readchannel.read(buffer);
                if(len==-1) {
                    break;
                }
                for(int i=0;icatch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java基础)