package example1.java;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
	public static void main(String args[]) throws Exception {
		// 取得ディレクトリとコピー先ディレクトリになります。
		// それぞれの環境で変更してください
		File inboxDirectory = new File("inbox");
		File outboxDirectory = new File("outbox");
		outboxDirectory.mkdir();
		File[] files = inboxDirectory.listFiles();

		for (File source : files) {

			// 出力ファイル名は拡張子を日付に変える
			Date date = new Date();
			SimpleDateFormat sdf1 = new SimpleDateFormat(
					"yyyyMMdd'-'HH'.'mm'.'ss");

			String[] strArray = source.getName().split("\\.");
			String destFileName = "";
			if (strArray.length == 1) {
				destFileName = strArray[0];
			} else {
				for (int i = 0; i < strArray.length - 1; i++) {
					destFileName += destFileName.concat(strArray[i]);
				}
			}
			destFileName = destFileName.concat("." + sdf1.format(date));

			File dest = new File(outboxDirectory.getPath() + File.separator
					+ destFileName);
			// ファイルのコピーを実施
			copyFile(source, dest);
		}
	}

	private static void copyFile(File source, File dest) throws IOException {
		OutputStream out = new FileOutputStream(dest);
		byte[] buffer = new byte[(int) source.length()];
		FileInputStream in = new FileInputStream(source);

		in.read(buffer);
		try {
			out.write(buffer);
			System.out.println("Copy from " + source.getAbsolutePath() + " To "
					+ dest.getAbsoluteFile());
		} finally {
			out.close();
			in.close();
		}
	}
}