zoukankan      html  css  js  c++  java
  • 实现文件拷贝

    方法一: 单字节逐一拷贝

    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// 将文件的源和目的位置初始化到file数组中
    		String [] str = {"F:\demo\demo.txt","F:\demo\Demo1.txt"};
    		if (str.length != 2) {
    			System.out.println("命令执行错误");
    			System.exit(1);// 退出程序
    		}
    		File inFile = new File(str[0]); // 源文件
    		if(!inFile.exists()) { //源文件是否存在
    			System.out.println("源文件不存在");
    			System.exit(1);
    		}
    		File outFile = new File(str[1]);
    		if (!outFile.getParentFile().exists()) { // 目的是否存在
    			outFile.getParentFile().mkdirs(); //创建目录以及文件
    		}
    		InputStream input = new FileInputStream(inFile);
    		OutputStream output = new FileOutputStream(outFile);
    		// 完成两个文件的实例对象
    		int temp = 0 ; //保存读取的内容
    		while ((temp = input.read()) != -1) { // 每次读取单个字节,输出到目标文件中
    			output.write(temp);
    		}
    		input.close();
    		output.close();
    	}	
    }
    
    • 遇到大容量的文件时,拷贝速度非常慢!!!

    方法二:部分数据拷贝

    public class TestDemo {
    	public static void main(String [] args) throws IOException {
    		// 将文件的源和目的位置初始化到file数组中
    		String [] str = {"F:\demo\demo.txt","F:\demo\Demo1.txt"};
    		if (str.length != 2) {
    			System.out.println("命令执行错误");
    			System.exit(1);// 退出程序
    		}
    		File inFile = new File(str[0]); // 源文件
    		if(!inFile.exists()) { //源文件是否存在
    			System.out.println("源文件不存在");
    			System.exit(1);
    		}
    		File outFile = new File(str[1]);
    		if (!outFile.getParentFile().exists()) { // 目的是否存在
    			outFile.getParentFile().mkdirs(); //创建目录以及文件
    		}
    		InputStream input = new FileInputStream(inFile);
    		OutputStream output = new FileOutputStream(outFile);
    		// 完成两个文件的实例对象
    		int temp = 0 ; //保存读取的内容
    		byte [] data = new byte[1024]; // 每次读取1024字节
    		while ((temp = input.read(data)) != -1) { // 每次读取单个字节,输出到目标文件中
    			output.write(data,0,temp);
    		}
    		input.close();
    		output.close();
    	}
    }
    
  • 相关阅读:
    MaaS系统概述
    流处理认识
    事务补偿
    Hystrix原理与实战
    RPC概念和框架
    git remote: error: hook declined to update
    Unity CombineTexture
    Windows Powershell统计代码行数
    unity面试题二
    unity面试题一
  • 原文地址:https://www.cnblogs.com/wangyuyang1016/p/11160333.html
Copyright © 2011-2022 走看看