【Java笔记】IO流中文件复制及异常处理

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

public class Main {
	public static void main(String[] args) throws IOException {
		// 创建字节流的引用变量
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			// 绑定数据源和目标文件
			fis = new FileInputStream("d:\\a.txt");
			fos = new FileOutputStream("d:\\b.txt");
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = fis.read(bytes)) != -1) {// 读取数据源字节
				fos.write(bytes, 0, len);// 写入字节到目标文件
			}
		} catch (IOException ex) {
			System.out.println(ex);
			throw new RuntimeException("文件复制失败");
		} finally {
			try {
				fis.close();
			} catch (Exception ex) {
				throw new RuntimeException("关闭输入流失败!");
			} finally {
				try {
					fos.close();
				} catch (Exception ex) {
					throw new RuntimeException("关闭输出流失败!");
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42370146/article/details/83346749