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();
    	}
    }
    
  • 相关阅读:
    Ubuntu操作系统如何设置默认启动内核
    设置和取消环境变量
    vue create与vue init的区别
    base64 编解码
    获取url中的参数
    ubuntu账户密码正确但是登录不了怎么办
    斐波那契数列的递推式-----动态规划
    Round-Robin轮询调度法及其实现原理
    MySql中float类型的字段的查询
    使用 Python 从网页中提取主要文本内容
  • 原文地址:https://www.cnblogs.com/wangyuyang1016/p/11160333.html
Copyright © 2011-2022 走看看