利用java流实现文本文件/二进制文件的复制

1、文本文件的复制

package test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyChar {

	public static void main(String[] args){
		
		String sourceTxt = "D:/workspace1/project1/src/source.txt";
		String destTxt = "D:/workspace1/project1/src/dest.txt";
		
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new FileReader(sourceTxt));
			bw = new BufferedWriter(new FileWriter(destTxt));
			
			String line = null;
			while((line = br.readLine()) != null){
				bw.write(line);
				bw.newLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(bw != null){
				try {
					bw.flush();
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

 

2、二进制文件的复制

package test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyByte {

	public static void main(String[] args){
		
		String sourceTxt = "D:/workspace1/project1/src/source.jpg";
		String destTxt = "D:/workspace1/project1/src/dest.jpg";
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(sourceTxt));
			bos = new BufferedOutputStream(new FileOutputStream(destTxt));
			
			int hasRead = 0;
			byte b[] = new byte[1024];
			while((hasRead = bis.read(b)) > 0){
				bos.write(b, 0, hasRead);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(bos != null){
				try {
					bos.flush();
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(bis != null){
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

你可能感兴趣的:(java)