Java文件复制的三种方法

  • Post author:
  • Post category:java


//1、使用nio进行文件复制。这种复制后,源文件还在。
public void copy(){
        String path = "D:\\xx";
        try(FileChannel in = new FileInputStream(path+"\\src.txt").getChannel();
            FileChannel out = new FileOutputStream(path+"\\dest.txt", true).getChannel()){
            out.transferFrom(in, 0, in.size());
            System.out.println("拷贝完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//使用io的方式复制文件,复制后源文件也还在。
private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }
 File sourceFile = new File("D:\\xx\\gis_feature.sql");//目录A
 File destFile = new File("D:\\xx\\lib\\gis_feature.sql");//目录B
 sourceFile.renameTo(destFile);//将文件从A剪切到B。源文件不在了。



版权声明:本文为weixin_42000850原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。