java合并文件

java Io  将n个文件和并问题



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

public class StreamDemo {

	/**
	 * @param args
	 */
	
	
	public static void getmerge(String[] filenames, String targetfilename) throws Exception{
		File filein = null;
		File fileout = new File(targetfilename);
		FileOutputStream out = new FileOutputStream(fileout);
		for(int i=0 ; i < filenames.length; i++){
			filein = new File(filenames[i]);
			FileInputStream in = new FileInputStream(filein);
			int c ;
			while((c = in.read()) != -1){
				out.write(c);
			}
			in.close();
		}
		out.close();
	}
	public static void getmessage(String filename){
		File file = new File(filename);
		BufferedReader reader = null;
		try{
			reader = new BufferedReader(new FileReader(file));
			String line = null;
			while((line = reader.readLine()) != null){
				System.out.println(line);
			}
			reader.close();
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			if(reader != null){
				try{
					reader.close();
				}catch(IOException e){
					
				}
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		String[] fileNames = { "D:/temp/1.txt", "D:/temp/2.txt",
			    "D:/temp/3.txt", "D:/temp/4.txt" };
			  String newFileName = "D:/temp/total.txt";
			  StreamDemo.getmerge(fileNames, newFileName);
			  StreamDemo.getmessage(newFileName);
	}

}



你可能感兴趣的:(java合并文件)