How to remove extra empty lines from XML file?

前端 未结 9 1127
再見小時候
再見小時候 2020-12-08 11:22

In short; i have many empty lines generated in an XML file, and i am looking for a way to remove them as a way of leaning the file. How can i do that ?

For detailed

9条回答
  •  死守一世寂寞
    2020-12-08 11:48

    When i used dom4j to remove some elements and i met the same question,the solution above not useful without adding some other required jars.Finally,i find out a simple solution only need to use JDK io pakage:

    1. use BufferedReader to read the xml file.
    StringBuilder stringBuilder = new StringBuilder();
    FileInputStream fis = new FileInputStream(outFile);
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(isr);
    String s;
    while ((s = br.readLine()) != null) {
      if (s.trim().length() > 0) {
        stringBuilder.append(s).append("\n");
      }
    }
    
    1. write the string to the xml file
    OutputStreamWriter osw = new OutputStreamWriter(fou);
    BufferedWriter bw = new BufferedWriter(osw);
    String str = stringBuilder.toString();
    bw.write(str);
    bw.flush();
    
    1. remember to close all the stream

提交回复
热议问题