因为你的题目没有描述清楚,所以 我假设 碎片文件 都是以
xxxx
xxxx
...
这样的格式编写的,现在需要读取各个碎片文件 合并到一个文件中去并按照序号排序。
package org.vic.reader;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.Closeable;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class Reader {private String[] paths;public Reader(String... paths){this.paths = paths;}public void mergeFile(String destFilePath) throws InterruptedException, ExecutionException, IOException{if(paths != null && paths.length > 0){List>> futures = new ArrayList<>();List errors = new ArrayList<>();ExecutorService service = Executors.newCachedThreadPool();for(String path : paths) {File file = new File(path);if(file.exists()){Tasker tasker = new Tasker(file);Future> result = service.submit(tasker);futures.add(result);}else{errors.add("path : " + path + " is not existing!");break;}}service.shutdown();if(errors.size() == 0){List strings = new ArrayList<>();for(Future> f : futures){strings.addAll(f.get());}/*如果文件是按照1. xxx 2. vvv3. bbb的格式书写的*/Collections.sort(strings, new NumberComparer());File file = new File(destFilePath);if(!file.exists()){file.createNewFile();}BufferedWriter writer = new BufferedWriter(new FileWriter(file));for(String content : strings){writer.write(content + "\n");}Reader.closeStreams(writer);} else {for(String error : errors){System.out.println(error);}}}else{System.out.println("no paths!");}}public static final void closeStreams (Closeable... streams) {if(streams != null && streams.length > 0){for(Closeable c : streams){if(c != null){try {c.close();} catch (IOException e) {e.printStackTrace();}}}}}public static void main(String[] args) {String[] paths = {"碎片文件1路径","碎片文件2路径","碎片文件3路径"};String destFilePath = "合并后文件路径";Reader reader = new Reader(paths);try {reader.mergeFile(destFilePath);} catch (InterruptedException | ExecutionException | IOException e) {e.printStackTrace();}}}class Tasker implements Callable> {private File file;public Tasker(File file){this.file = file;}@Overridepublic List call() throws Exception {BufferedReader reader = new BufferedReader(new FileReader(file));List res = new ArrayList<>();String temp = "";while((temp = reader.readLine()) != null){res.add(temp);}Reader.closeStreams(reader);return res;}}class NumberComparer implements Comparator {@Overridepublic int compare(String o1, String o2) {if(getNumber(o1) > getNumber(o2)){return 0;}return -1;}private Integer getNumber(String o){String numberString = o.substring(0,o.indexOf("."));return Integer.valueOf(numberString);}}
取消
评论