简体   繁体   English

关于将多个文件拼接成一个文件

[英]Regarding stitching of multiple files into a single file

I work on query latencies and have a requirement where I have several files which contain data. 我处理查询延迟,并且有一个要求,其中有几个包含数据的文件。 I want to aggregate this data into a single file. 我想将此数据聚合到一个文件中。 I use a naive technique where I open each file and collect all the data in a global file. 我使用一种幼稚的技术来打开每个文件,并将所有数据收集到一个全局文件中。 I do this for all the files but this is time taking. 我对所有文件都这样做,但这很花时间。 Is there a way in which you can stitch the end of one file to the beginning of another and create a big file containing all the data. 有没有一种方法可以将一个文件的结尾缝合到另一个文件的开头,并创建一个包含所有数据的大文件。 I think many people might have faced this problem before. 我认为很多人以前可能已经遇到过这个问题。 Can anyone kindly help ? 任何人都可以帮忙吗?

I suppose you are currently doing the opening and appending by hand; 我想您当前正在手动进行打开和添加操作; otherwise I do not know why it would take a long time to aggregate the data, especially since you describe the amount of files using multiple and several which seem to indicate it's not an enormous number. 否则我不知道为什么它会需要很长的时间来汇总数据,特别是因为你描述使用多个几个这似乎表明它不是一个数量庞大的文件量。

Thus, I think you are just looking for a way to automatically to the opening and appending for you. 因此,我认为您只是在寻找一种自动为您打开和添加附件的方法。 In that case, you can use an approach similar to below. 在这种情况下,您可以使用类似于以下的方法。 Note this creates the output file or overwrites it if it already exists, then appends the contents of all specified files. 请注意,这将创建输出文件或将其覆盖(如果已存在),然后附加所有指定文件的内容。 If you want to call the method multiple times and append to the same file instead of overwriting an existing file, an alternative is to use a FileWriter instead with true as a second argument to its constructor so it will append to an existing file. 如果要多次调用该方法并追加到同一个文件中而不是覆盖现有文件,则另一种方法是使用FileWriter而不是将true作为其构造函数的第二个参数,以便将其追加到现有文件中。

void aggregateFiles(List<String> fileNames, String outputFile) {
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(outputFile);
        for(String fileName : fileNames) {
            Path path = Paths.get(fileName);
            String fileContents = new String(Files.readAllBytes(path));
            writer.println(fileContents);
        }
    } catch(IOException e) {
        // Handle IOException
    } finally {
        if(writer != null) writer.close();
    }
}

List<String> files = new ArrayList<>();
files.add("f1.txt");
files.add("someDir/f2.txt");
files.add("f3.txt");

aggregateFiles(files, "output.txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM