`

JAVA_IO

 
阅读更多
/**
 * 1、编写程序,将一个目录及其子目录下的所有 txt 类型的文本文件中的内容合并到若干个新的文本文件中,
 *    当第一个新产生的文件存储的内容达到 1M 时,剩下的内容存储到第二个新的文件中,依次往下,
 *    新产生的文本文件名依次为 1.txt、2.txt
 * */
public class TestIO {

	
	
	
	private static int number = 1;

	public static void main(String[] args) {
		
		List<String> result = new ArrayList<String>();
		getFilePath("E:\\abc",result);
		readToDest(result);
	}
	
	//得到路径下所有 txt文件的绝对路径
	public static void  getFilePath(String dirs,List<String> slist)
	{
		
		File dir =new File(dirs);
		File[] files = dir.listFiles();
		for(File f :files)
		{
			if(f.isFile() && f.getName().endsWith("txt"))
			{
				slist.add(f.getAbsolutePath());
			}
			else if(f.isDirectory())
			{
				getFilePath(f.getAbsolutePath(),slist);
			}
		}
	}
	public static void readToDest(List<String> src)
	{
		
		for(String dest : src)
		{
			String newFilePath = "D://ttt//" + number + ".txt";
			File newFile = new File(newFilePath);
			if(!newFile.exists())
			{
				try {
					newFile.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			// 旧文件输入流
			try {
				FileInputStream fIn = new FileInputStream(new File(dest));
				BufferedInputStream bIn = new BufferedInputStream(fIn);
				// 新文件输出流
				FileOutputStream fOut = new FileOutputStream(newFilePath, true);
				BufferedOutputStream bOut = new BufferedOutputStream(fOut);
				byte[] bytes = new byte[1024];
				while (bIn.read(bytes) != -1) {
					if (newFile.length() > 1024 * 1024) {
						newFilePath = "D://ttt//" + ++number + ".txt";
						newFile = new File(newFilePath);
						fOut = new FileOutputStream(newFilePath);
						bOut = new BufferedOutputStream(fOut);
						bOut.write(bytes);
					} else 
					{
						bOut.write(bytes);
					}
					bOut.flush();
				}
				bIn.close();
				bOut.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}
分享到:
评论
2 楼 love_rain_boy 2011-09-25  
不好意思刚才说的有点问题,现在好了
int len;
while ((len=bIn.read(bytes) )!= -1) {
if (newFile.length() > 1024 * 1024) {
newFilePath = "D://ttt//" + ++number + ".txt";
newFile = new File(newFilePath);
fOut = new FileOutputStream(newFilePath);
bOut = new BufferedOutputStream(fOut);
bOut.write(bytes,0,len);//这里应该写入的是文件的实际长度,而不是bytes的数组长度
} else
{
bOut.write(bytes);//这里同上
}
bOut.flush();
}
1 楼 love_rain_boy 2011-09-25  
谢谢你的思路提醒了我,不过我感觉你在readToDest方法中的write方法用write(buf,0,len)更好一点啊。
while (bIn.read(bytes) != -1) {
if (newFile.length() > 1024 * 1024) {
newFilePath = "D://ttt//" + ++number + ".txt";
newFile = new File(newFilePath);
fOut = new FileOutputStream(newFilePath);
bOut = new BufferedOutputStream(fOut);
bOut.write(bytes,0,len);//这里应该写入的是文件的实际长度,而不是bytes的数组长度
} else
{
bOut.write(bytes,0,len);//这里同上
}
bOut.flush();
}

相关推荐

Global site tag (gtag.js) - Google Analytics