JAVA NIO

转载请注明出处:https://i.cnblogs.com/EditPosts.aspx?opt=1

我们在学习的过程中可以形成自己的代码库,即将一些常用的类,函数,接口,配置文件等单独拎出来,下次使用时直接复制过来,这样就可以重复造轮子,早点下班回家。

java NIO是一个高效的处理文件的API, 比传统文件流要高效许多。

public class MyFileTools {
    
    public void copyFile(String inFile,String outFile,boolean tail){
        FileInputStream fin = null;
        FileOutputStream fout = null;
        
        FileChannel fcin = null;
        FileChannel fcout = null;
        
        try {
            fin = new FileInputStream(inFile);
            fout = new FileOutputStream(outFile,tail);
            
            fcin = fin.getChannel();
            fcout = fout.getChannel();
            
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while(true){
                buffer.clear();
                int read = fcin.read(buffer);
                if(read == -1){
                    break;
                }
                buffer.flip();
                fcout.write(buffer);
                
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fcin != null){
                try {
                    fcin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fcout != null){
                try {
                    fcout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void main(String[] args){
        MyFileTools mft = new MyFileTools();
        mft.copyFile("/sandbox-local/rding/HelloCopy.py", "/sandbox-local/rding/HelloPython2.py",true);
        
    }

}
原文地址:https://www.cnblogs.com/lfdingye/p/7550898.html