文件的复制(输入输出流)

本文详细阐述了Java中复制文件的基本原理,并通过代码示例展示了如何使用InputStream和OutputStream进行文件复制。同时,介绍了Java7引入的自动关闭资源的try语句,简化了资源管理,提高了代码的可读性和健壮性。

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

字节流(操作字节,也可以操作字符,但是可能会产生乱码)主要有InputStream和OutputStream作为抽象基类,访问时是FileInputStream、FileOutputStream两个实现类;字符流(操作字符)主要由Reader和Writer作为抽象基类,FileReader(读取时可以一次读一行readLine())、FlieWriter作为实现类。

java中复制文件原理是就是打开一个旧文件,用输入流FileInputStream读取数据,然后在打开一个输出流FileOutputStream把数据放进去。可以理解为是两个水池,中间用byte[] 进行取水,每次取一个字节。记得放在try catch块中,关闭流的方法放在finally中。

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


/**
 * 复制文件
 * @author zxc
 *
 */
public class CopyFile {


	<pre name="code" class="java"><span style="white-space:pre">	</span>public static void main(String[] args){
		File oldFile = new File("c:" + File.separator + "1.ini");
		FileInputStream inputStream = null;
		FileOutputStream outputStream = null;
		if (oldFile.exists()) {
			try{
				inputStream = new FileInputStream(oldFile);
				outputStream = new FileOutputStream("f:" + File.separator + oldFile.getName());
				byte[] buffer = new byte[1024];
				int leath = 0;
				while ((leath = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally{
				try {
					inputStream.close();
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}else {
			System.out.println("复制的文件不存在");
		}
		
	}

}
 


Java 7改写了所有的IO资源类,它们都实现了AutoCloseable接口,因此都可以通过自动关闭资源的try语句来关闭这些IO流

<span style="white-space:pre">	</span>public static void main(String[] args){
		File oldFile = new File("c:" + File.separator + "1.ini");
		FileInputStream inputStream = null;
		FileOutputStream outputStream = null;
		if (oldFile.exists()) {
			try(<pre name="code" class="java"><span style="white-space:pre">				</span>inputStream = new FileInputStream(oldFile);
				outputStream = new FileOutputStream("f:" + File.separator + oldFile.getName());
){byte[] buffer = new byte[1024];int leath = 0;while ((leath = inputStream.read(buffer)) != -1) {outputStream.write(buffer);}} catch (IOException e) {e.printStackTrace();} }else {System.out.println("复制的文件不存在");}}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值