使用IO流进行文件的拷贝

直接上代码:

package com.yyj.IO;

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


public class IOTest {
	public static void main(String[] args)   {
		String filePath = "E:\\IO.txt";
		File file = new File(filePath);
		if(file.exists()){
			System.out.println("文件存在!");
		}
		FileInputStream is = null;
		FileOutputStream os = null;
		
		int temp =0;
		byte[] bytes = new byte[1024];
		
		try {
			is = new FileInputStream(filePath);
			os = new FileOutputStream("E:\\IOs.txt");
			while((temp = is.read(bytes))!=-1){
				os.write(bytes, 0, temp);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}


### Java使用 IO 实现文件拷贝Java 中,可以通过字节或字符来完成文件的复制工作。对于二进制文件(如图像、视频),应采用 `FileInputStream` 和 `FileOutputStream` 来执行读取和写入操作;而对于纯文本文件,则可以选择更高效的 `FileReader` 和 `FileWriter` 进行处理[^4]。 下面是一个利用字节进行文件复制的具体实例: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileCopyExample { public static void main(String[] args) { String sourceFilePath = "source.txt"; String destinationFilePath = "destination.txt"; try (FileInputStream fis = new FileInputStream(sourceFilePath); FileOutputStream fos = new FileOutputStream(destinationFilePath)) { byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } System.out.println("文件已成功复制!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 此代码片段展示了如何创建两个文件对象——一个是用于源文件的输入 (`FileInputStream`) ,另一个是目标文件的输出(`FileOutputStream`). 接着定义了一个缓冲区数组,在循环体内不断从输入中读取数据并将其写入到输出直到整个文件被完全传输完毕[^1]. 当涉及到大容量的数据或者追求更高的性能时,建议增加缓存大小以减少磁盘I/O次数,并考虑关闭自动刷新功能以便手动控制何时将内容刷入目的地文件.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值