【问题标题】:Java inputstream/outputstream write to file with same nameJava输入流/输出流写入同名文件
【发布时间】:2018-05-25 13:06:21
【问题描述】:

我有一些代码通过文件树并将根添加到没有它们的 xml 文件中。我的问题是当我尝试从输入流写入输出流时。我想用更新的版本(添加了根的那个)替换当前的 xml 文件。我认为如果我使输出流与输入流相同,则会出现问题。直觉上,这似乎是一个问题。如果没有,请告诉我。

我该如何解决这个问题?我怎样才能基本上“更新”xml文件,实际上覆盖另一个?我在这里查看了其他答案,但还没有走远。

private static void addRootHelper(File root){
    FileInputStream fis;
    List<InputStream> streams;
    InputStream is;
    OutputStream os;

    File[] directoryListing = root.listFiles();
    if (directoryListing != null) {
        for (File child : directoryListing) {
            addRootHelper(child);
        }
    }
    else {
        try{
            // Add root to input stream and create output stream
            fis = new FileInputStream(root);
            streams = Arrays.asList(new ByteArrayInputStream("<root>".getBytes()),fis, new ByteArrayInputStream("</root>".getBytes()));
            is = new SequenceInputStream(Collections.enumeration(streams));
            os = new FileOutputStream(root.getAbsolutePath());

            // Write from is -> os
            byte[] buffer = new byte[1024];
            int bytesRead;

            // Read from is to buffer
            while((bytesRead = is.read(buffer)) !=-1){
                os.write(buffer, 0, bytesRead);
            }
            is.close();
            os.flush();
            os.close();
            System.out.println("Added root to " + root.getName());

        }
        catch(IOException ex){
            ex.printStackTrace();
        }
    }
}

【问题讨论】:

  • 如何在读取文件的同时写入文件?您可以做的是将输出写入不同的临时文件。然后删除原始文件并将临时文件重命名为原始名称。或者如果文件足够小,将整个文件加载到内存中,或者完全在内存中处理,关闭文件,然后写回它。
  • 是的,我认为这会是个问题。我考虑了您的解决方案,但想知道是否有更优雅的方法。如果没有,那当然也可以!

标签: java xml file inputstream outputstream


【解决方案1】:

如果您不想使用流行的临时文件方法,那么您可以随时读取整个文件,然后再写回它。

这是一个简单的实现。

public static void addRootTag(File xml) throws IOException {
    final List<String> lines = new ArrayList<>();;
    try (Scanner in = new Scanner(xml)) {
        while (in.hasNextLine())
            lines.add(in.nextLine());
    }

    try (PrintStream out = new PrintStream(xml)) {
        out.println("<root>");
        for (String line : lines) {
            // indentation, if you want
            out.print("    ");
            out.println(line);
        }
        out.println("</root>");
    }
}

【讨论】:

    猜你喜欢
    • 2012-05-16
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 2012-04-02
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多