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

版权声明:版权所有@万星明 https://blog.csdn.net/qq_19533277/article/details/83242875

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

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();
		}
		
	} 	
}

猜你喜欢

转载自blog.csdn.net/qq_19533277/article/details/83242875