【文件属性】:
文件名称:卫斯理合集 倪匡
文件大小:23.44MB
文件格式:TXT
更新时间:2021-11-12 06:37:39
java 卫斯理
合并文本代码,读取文件,合并为一个txt
public static final int BUFSIZE = 1024 * 8;
public static void mergeFiles(String outFile, ArrayList files) {
FileChannel outChannel = null;
try {
outChannel = new FileOutputStream(outFile).getChannel();
for(String f : files){
ByteBuffer wrap = ByteBuffer.wrap("\r\n".getBytes());
outChannel.write(wrap);
FileChannel fc = new FileInputStream(f).getChannel();
ByteBuffer bb = ByteBuffer.allocate(BUFSIZE);
while(fc.read(bb) != -1){
bb.flip();
outChannel.write(bb);
bb.clear();
}
fc.close();
}
out.println("Merged!! ");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {if (outChannel != null) {outChannel.close();}} catch (IOException ignore) {}
}
}
public static void main(String[] args) {
ArrayList files = getFiles("D:/test/");
mergeFiles("D:/output.txt", files);
}
public static ArrayList getFiles(String path) {
ArrayList files = new ArrayList();
File file = new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
// System.out.println("文 件:" + tempList[i]);
files.add(tempList[i].toString());
}
if (tempList[i].isDirectory()) {
// System.out.println("文件夹:" + tempList[i]);
}
}
return files;
}