将制定文件路径下的文件内容合并到一个文件

import java.io.*;
class  UnionDemo
{
	public static void main(String[] args) 
	{
		String srcFilePath = "D:\\Work\\";
		String tarFilePath = "D:\\Test\\";
		File srcFile = new File(srcFilePath);
		File tarFile = new File(tarFilePath);
		BufferedWriter bw=null;
		try
		{
			if(tarFile.isDirectory())
				tarFile.mkdir();
			else
				tarFile.createNewFile();
		    bw = new BufferedWriter(new FileWriter(new File(tarFile,"union.txt")));

		}
		catch (IOException ex)
		{
		}
		unionFile(srcFile,bw);
	}

	public static void unionFile(File srcFile,BufferedWriter bw)
	{
		try
		{
			File[]files = srcFile.listFiles();
			for(File temFile : files)
			{
				if(temFile.isDirectory())
					unionFile(srcFile,bw);
				else
				{
					BufferedReader br = new BufferedReader(new FileReader(temFile));
					String line = null;
					while((line = br.readLine()) != null)
						bw.write(line);
					if(br != null)br.close();
					if(bw != null)bw.close();
				}
			}
		}
		catch (IOException ex)
		{
		}
		
	}
}

posted @ 2015-01-22 13:52  静以养身 俭以养德  阅读(289)  评论(0编辑  收藏  举报