ファイルのコピー

2549 ワード

:
, , IO , 。 , , , 。 , , , !

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileUtils {
	/*
	 * srcFile     
	 * destFile     
	 *  num         (  KB)
	 */

	public static void copyFile(File srcFile, File destFile, int num) {

		if (!srcFile.exists()) {
			throw new IllegalArgumentException(srcFile + "   ");
		}
		if (!srcFile.isFile()) {
			throw new IllegalArgumentException(srcFile + "    ");
		}

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		byte[] buf = new byte[num * 1024];
		int len = 0;

		try {
			bis = new BufferedInputStream(new FileInputStream(srcFile));
			bos = new BufferedOutputStream(new FileOutputStream(destFile));
			while ((len = bis.read(buf, 0, buf.length)) != -1) {
				bos.write(buf, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bis.close();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void copyTextFile(File srcFile, File destFile, int num) {

		BufferedReader br = null;
		BufferedWriter bw = null;
		char[] cbuf = new char[num * 1024];
		int len = 0;

		try {
			br = new BufferedReader(new FileReader(srcFile));
			bw = new BufferedWriter(new FileWriter(destFile));
			while ((len = br.read(cbuf, 0, cbuf.length)) != -1) {
				bw.write(cbuf, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}