【问题标题】:How to merge multiple files in another new one in java?如何在java中将多个文件合并到另一个新文件中?
【发布时间】:2019-05-07 14:35:27
【问题描述】:

我想合并一些看起来像这样的文件:

File 1
line 01
line 02
line 03

File2
line 04
line 05

输出应该是这样的:

NewFile
line 01
line 02
line 03
line 04
line 05

我的算法接收本地目录的 URL,然后遍历它以仅获取具有 json 扩展名的文件并将它们合并。例如,在这个 URL 中有两个 json 文件,但最后一个附加到新文件中。

这是我目前的代码

public class ReadFiles {
    static FileWriter fileWriter;
    public static void main(String... args) throws IOException, InterruptedException, ParseException {
        File[] files = new File("C:\\xampp\\htdocs\\project-js\\blocks\\actions\\Application").listFiles();
        showFiles(files);
    }

    public static void showFiles(File[] files) throws FileNotFoundException, IOException, ParseException {
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("Directory: " + file.getName());
                showFiles(file.listFiles());

            } else {
                if (file.getName().endsWith("json")) { // find only those with json extensions
                    System.out.println(file.getName());

                    JSONParser parser = new JSONParser();

                    fileWriter = new FileWriter("C:\\xampp\\htdocs\\project-js\\blocks\\actions\\Application\\ApplicationDesc.js");
                    fileWriter.write(parser.parse(new FileReader(file)).toString());
                    fileWriter.close();

                    try {
                        System.out.println(parser.parse(new FileReader(file)));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }  
            }
        }
    }
}

【问题讨论】:

  • 你不能只是将 json 文件相互附加,这会创建一个无效的 json。
  • 然后会发生什么?之后你需要它是有效的json吗?需要用append打开FileWriter吗?
  • 这些 json 文件有多大?
  • 如果您发布解决方案或接受答案作为解决方案,这对我们所有人都会更好。这样其他人遇到这个问题就可以解决这个问题。

标签: java


【解决方案1】:

您只需将第二个文件的内容附加到第一个文件的末尾即可。

请注意,一个 json 内容文件与另一个 json 内容文件合并会产生一个非 json 内容文件。

例如a.json:

{ "name":"John" }

和 b.json:

{ "name":"Anna" }

产生一个combined.json

{ "name":"John" }
{ "name":"Anna" }

这不是一个有效的 json。

如果您有一个 json 对象数组,也会发生这种情况:

a.json:

[{ "name":"John" }, { "name":"Anna" }] 

b.json

[{ "name":"Keith"}]

以及它们的组合:

[{ "name":"John" }, { "name":"Anna" }] 
[{ "name":"Keith"}]

这不是一个有效的 json 内容文件

【讨论】:

  • 这是我只希望将 json 文件合并在一起的场景。请问有什么办法吗?
【解决方案2】:

该代码中的问题:

  fileWriter = new FileWriter("C:\\xampp\\htdocs\\project-js\\blocks\\actions\\Application\\ApplicationDesc.js");
  fileWriter.write(parser.parse(new FileReader(file)).toString());
  fileWriter.close();

是不是每次都会创建一个新的 FileWriter 并覆盖之前的文件。您可以使用以下方法创建 fileWriter:

fileWriter = new FileWriter("C:\\xampp\\htdocs\\project-js\\blocks\\actions\\Application\\ApplicationDesc.js",true); //The true in the end is to append to file

或者在循环外创建fileWriter,然后在循环结束时关闭它。如果文件具有您示例中的内容,那么您会没事的。如果它们是 JSON 文件并且您期望得到有效的 json 结果,那么您不能只将它们附加到一个大文件中

【讨论】:

    【解决方案3】:

    您可以收集所有文件的文本。

    为此,您需要逐个读取每个文件并提取其内容

    使用它来将单个文件的内容提取为字符串

    private static String readFileAsString(String filePath){
        StringBuilder contentBuilder = new StringBuilder();
    
        try (Stream<String> stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8)){
            stream.forEach(s -> contentBuilder.append(s).append("\n"));
        }
        catch (IOException e){
            e.printStackTrace();
        }
    
        return contentBuilder.toString();
    }
    

    您可以为每个提取的字符串创建一个 JSONObject (org.json)

    JSONObject jsonObj = new JSONObject(extractedString);
    

    然后将 jsonObj 存储在 List 中。

    要使用 JSONObject,请将其添加到您的 pom.xml 或手动下载 jars

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180813</version>
    </dependency>
    

    使用以下方法从列表中合并 JSONObjects

    public static JSONObject mergeJSONObjects(JSONObject json1, JSONObject json2) {
        JSONObject mergedJSON = new JSONObject();
        try {
            mergedJSON = new JSONObject(json1, JSONObject.getNames(json1));
            for (String key : JSONObject.getNames(json2)) {
                mergedJSON.put(key, json2.get(key));
            }
    
        } catch (JSONException e) {
            throw new RuntimeException("JSON Exception" + e);
        }
        return mergedJSON;
    }
    

    然后将最终的String写入一个文件。

    使用类似的东西

     BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt"));
     writer.write();
     writer.close();
    

    这可行,但文件的大小应该很小,对于更大的文件,您需要找到更好的解决方案。

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多