[英]Java inputstream/outputstream write to file with same name
我有一些通過文件樹的代碼,並將根添加到沒有它們的xml文件中。 我的問題是當我嘗試從輸入流寫入輸出流時。 我想用更新的版本(添加了根目錄的文件)替換當前的xml文件。 我認為如果將outputstream和inputstream設為相同的文件,則會出現問題。 憑直覺,這似乎是一個問題。 如果沒有,請告訴我。
我該如何補救? 我如何實質上可以“更新” 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();
}
}
}
如果您不想使用流行的臨時文件方法,則始終可以只讀取整個文件,然后再寫回該文件。
這是一個簡單的實現。
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>");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.