2017-08-25 102 views
0

我使用BufferedReader將文檔的XML文本作爲字符串獲取。我嘗試使用IO將相同的XML字符串行寫入另一個XML文件,但我不能。我有以下employee.xml文件。可以將字符串行直接插入到XML文件中

<employee id="1" xmlns=""> 
    <firstname>James</firstname> 
    <lastname>Harley</lastname> 
    <email>[email protected]</email> 
    <department>Human Resources</department> 
    <salary>1000</salary> 
</employee> 

<employee id="2" xmlns=""> 
    <firstname>John</firstname> 
    <lastname>May</lastname> 
    <email>[email protected]</email> 
    <department>Logistics</department> 
    <salary>400</salary> 
</employee> 

我試圖讀取XML文件是與我的這種方法效果很好。

private static ArrayList<String> getXMLLines(String xmlFile) { 
    String line; 
    ArrayList<String> lines=new ArrayList<String>(); 

    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(xmlFile),"ISO-8859-1"))) { 
     br.readLine(); 
     while ((line = br.readLine()) != null) { 
     if(line.contains("xmlns=\"\"")){ 
       System.out.println(line); 
       line=line.replace("xmlns=\"\"",""); 
       System.out.println(line); 
      } 

      lines.add(line); 
     } 


    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return lines; 
} 

我的問題在於將這些字符串行寫入XML文件。我怎樣才能將這些字符串行寫入XML文件?

+0

因此,基本上你想要做的是將你的employees.xml文件的內容複製到另一個xml文件中,或者只是將你創建的XML文本寫入文件中? –

+0

我有這個ArrayList中包含XML標籤的字符串行:ArrayList lines = new ArrayList ();.現在,我想將這些字符串行寫入xml文件。 – islamuddin

+0

爲什麼不使用[Files.write](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java。 lang.Iterable-java.nio.file.OpenOption ...-)?如in,'Files.write(Paths.get(「data.xml」),lines)'。 – VGR

回答

-1

用這種方法創建一個IOUtils.java類:

public static void writeToFile (String filePath, String content) { 

    File file = new File (filePath); 

    try { 
     FileOutputStream fos = new FileOutputStream (file); 

     PrintWriter pw  = new PrintWriter (f); 
     pw.println (content); 
     pw.flush(); 

     closeQuietly (pw, f); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 

public static void closeQuietly (Closeable... closeables) { 
    if (closeables == null) { 
     return; 
    } 

    if (closeables.length == 0) { 
     return; 
    } 

    for (Closeable closeable : closeables) { 
     try { 
      closeable.close(); 
     } catch (IOException e) { 
     } 
    } 
} 
在你的代碼

然後:

IOUtils.writeToFile ("the_path_to_myFile.xml", myTextLines); 

我不知道你爲什麼使用這樣的List。您可能想考慮使用StringBuilder代替。