1. 程式人生 > >java 合併資料夾下多個檔案

java 合併資料夾下多個檔案

package test.com.whty.platform.modules.interfaces;


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 Test {
private static String filePath="d:\\1\\拆單檔案合併\\";
 static File rootFile=new File(filePath);
 static File[] listFile=rootFile.listFiles();

public static void merge(File[] fileNames, String TargetFileName)
throws Exception {
File fin = null;
// 構建檔案輸出流
File fout = new File(TargetFileName);
FileOutputStream out = new FileOutputStream(fout);
for (int i = 0; i < fileNames.length; i++) {
// 開啟檔案輸入流
fin = fileNames[i];
FileInputStream in = new FileInputStream(fin);
// 從輸入流中讀取資料,並寫入到檔案數出流中
int c=-1;
byte[] data=new byte[in.available()];
in.read(data);
out.write(data);
//while ((c = in.read()) != -1) {
//out.write(c);
//}
out.write("\r\n".getBytes());
in.close();
}
out.close();
System.out.println("合併檔案" + TargetFileName + "中的內容如下:");
}
public static void readFileMessage(String fileName) throws IOException {// 將合成的檔案中的內容讀出
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String string = null;
// 按行讀取內容,直到讀入null則表示讀取檔案結束
while ((string = reader.readLine()) != null) {
System.out.println(string);
}
reader.close();
} finally {
if (reader != null) {

reader.close();

}
}
}
public static void main(final String[] args) throws Exception {
// 合併檔案

String newFileName = "mergeSPLIT2.txt";
Test.merge(listFile, newFileName);
}






}