【发布时间】: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