java实现文件拷贝的两种方式(字符流与字节流)

简单实现了通过字节流与字符流两种方式拷贝文件

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/** 
* @author  万星明
* @version 创建时间:2018年10月19日 下午8:41:27 
*	1、编写一个程序,分别使用字节流和字符流拷贝一个文本文件
*	提示:
*		1、使用FileInputStream、FileOutputStream和FileReader、FileWriter分别进行拷贝
*		2、使用字节流拷贝时,定义一个1024长度的字节数组作为缓冲区,使用字符流拷贝,使用BufferedReader
*			和BufferedWriter包装流进行包装
*/
public class Copy {
	static Scanner sc = new Scanner(System.in);
	public static void main(String[] args) {
		
	}
	//使用字符流拷贝(BufferedReader与BufferedWriter)
	public static void ReaderWriterCopy() {
		System.out.println("请输入你需要拷贝的文件路径:");
		String oldPath = sc.next();
		System.out.println("请输入你拷贝到的文件路径:");
		String newPath = sc.next();
		
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new FileReader(oldPath));
			bw = new BufferedWriter(new FileWriter(newPath));
			
			String s = br.readLine();
			while(s!=null) {
				bw.write(s, 0, s.length());
				s = br.readLine();
			}
			System.out.println(oldPath+"文件拷贝完毕!");
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				br.close();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	//使用字节流拷贝(FileInputStream与FileOutputStream)
	public static void StreamCopy() throws Exception {
		System.out.println("请输入你需要拷贝的文件路径:");
		String oldPath = sc.next();
		System.out.println("请输入你拷贝到的文件路径:");
		String newPath = sc.next();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(oldPath);
			fos = new FileOutputStream(newPath);
			
			byte[] b = new byte[1024];
			int len = fis.read(b);
			while(len!=-1) {
				fos.write(b, 0, len);
				len = fis.read(b);
			}
			System.out.println(oldPath+"文件拷贝成功!");
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			fis.close();
			fos.close();
		}
		
	} 	
}
  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值