Java使用IO流拷贝文件和拷贝目录

本文详细介绍了如何使用Java的IO流进行文件和目录的拷贝操作,提供了完整的代码示例,包括文件流的读取与写入,以及目录递归拷贝的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java使用IO流拷贝文件和拷贝目录

文件的拷贝

import java.io.*;

public class Copy {
	public static void main(String[] args) {
		//调用方法执行文件复制
		boolean isSuccess = copyFile("要复制的文件(全路径或相对路径+文件名)","新的文件名");
		if(isSuccess) {
			System.out.println("文件复制成功!");
		}else {
			System.out.println("文件复制失败!");
		}
	}
	
	private static boolean copyFile(String oldFile, String newFile) {
		//定义输入输出流
		InputStream is = null;
		OutputStream os = null;
		StringBuilder builder = new StringBuilder();
		try {
			//读取
			is = new FileInputStream(oldFile);
			//输出
			os = new FileOutputStream(newFile);
			//定义字节缓冲数组
			byte[] flush = new byte[1024];
            //定义读取长度
            int len;
            while ((len = is.read(flush)) != -1) {
                os.write(flush, 0, len);
            }
            os.flush();
		}  catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //先开启的流 后关闭
            try {
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (new File(newFile).exists()) {
            return true;
        }
        return false;
	}
}

目录的拷贝

import java.io.*;
import java.time.Duration;
import java.time.Instant;

public class CopyDir {
    public static void main(String[] args) {
        Instant start = Instant.now();
        boolean isOk = dirOrFile("要复制的目录路径", "目标路径");
        if(isOk){
            System.out.println("目录复制完成!");
        }else {
            System.out.println("目录复制失败!");
        }
        Instant end = Instant.now();
        System.out.println("耗时:"+Duration.between(start,end).toMillis()+"毫秒!");
    }

	private static boolean copyDir(String oldDir, String newDir) {
        //定义流
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(oldDir);
            os = new FileOutputStream(newDir);
            //定义缓冲字节数组
            byte[] flush = new byte[1024];
            //定义读取长度
            int len;
            while ((len = is.read(flush)) != -1) {
                os.write(flush, 0, len);
            }
            //刷新流
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

	private static boolean dirOrFile(String oldDir, String newDir) {
        //定义写入写出文件
        File old = new File(oldDir);
        File copy = new File(newDir);
        //判断如果是目录的话 创建目录
        if (old.isDirectory()) {
            copy.mkdir();
            File[] files = old.listFiles();
            for (int i = 0; i < files.length; i++) {
                dirOrFile(files[i].getAbsolutePath(), newDir + "/" + files[i].getName());
            }
        }
        if (old.isFile()) {
            copyDir(oldDir, newDir);
        }
        if (old.length()==copy.length()){
            return true;
        }
        return false;
    }
}
### 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次数,并考虑关闭自动刷新功能以便手动控制何时将内容刷入目的地文件.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值