Java学习笔记之文件的复制

本文提供了一个使用Java实现的简单文件复制代码示例,详细解释了如何通过使用FileInputStream和FileOutputStream类来读取和写入文件内容,以及如何处理文件复制过程中的异常情况。

编写代码实现文件的复制功能

import java.io.*;
public class copyFile {
	public void copy(String oldPath,String newPath){
		try{
			int bytesum=0;
			int byteread=0;
			File oldFile=new File(oldPath);//用来判断文件是否存在,通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。
			if(oldFile.exists()){
				FileInputStream instream=new FileInputStream(oldPath);//<span style="font-size:10px;"><span style="font-family: Simsun; ">通过打开一个到实际文件的连接来创建一个 </span><code>FileInputStream</code></span>
				FileOutputStream fs=new FileOutputStream(newPath);

				byte[] buffer=new byte[1024];
				int length;
				while((byteread=instream.read(buffer))!=-1){//从此输入流中将最多 buffer.length 个字节的数据读入buffer 数组中,返回读入的数据流长度。
					bytesum+=byteread;//字节数 文件的大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				instream.close();
			}
		}catch(Exception e){
			System.out.println("复制文件出错!");
			e.printStackTrace();
		}
	}
	public static void main(String[] args){
		new copyFile().copy("", "");
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值