java学习笔记之实现文件的拷贝 2019/5/30

java学习笔记之实现文件的拷贝

利用前两天笔记中的FileInputStream和FileOutputStream实现文件的拷贝

实现

package learn.No173;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopy {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream("test01");// 文件读取的源(被复制文件)
			out = new FileOutputStream("TestMyOut");// 文件输出的源(目标文件)
			byte[] input = new byte[1024];// 每次复制1KB
			int len = 0;
			while ((len = in.read(input)) != -1) {
				out.write(input, 0, len);
			}
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {

			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		}
	}
}

结果:(成功复制)
在这里插入图片描述

将上面的代码封装到方法中

package learn.No173;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileCopy {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		File srca = new File("test01");
		File srcb = new File("TestCopy");
		CopyFile(srca, srcb);
	}

	public static void CopyFile(File resouse, File taget)// 将他们封装到方法中
	{
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(resouse);// 文件读取的源(被复制文件)
			out = new FileOutputStream(taget);// 文件输出的源(目标文件)
			byte[] input = new byte[1024];// 每次复制1KB
			int len = 0;
			while ((len = in.read(input)) != -1) {
				out.write(input, 0, len);
			}
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {

			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		}
	}
}

结果:
在这里插入图片描述
试试其他格式的文件(将pngtest.png文件复制到pngcopy)
在这里插入图片描述
运行之后(成功):
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值