2016-05-03 85 views
1

我想分割一个组合的文本文件。组合的文本文件里面有多个xml文件。我想分割<?xml version='1.0'?>这是组合文本文件中每个新xml的开始。不知道什么是最好的方式来做到这一点。目前这是我没有正确分割的东西。Combined Xml String Split Java

更新的代码工作(引号中的问题固定报价添加Pattern.quote):

Scanner scanner = new Scanner(new File("src/main/resources/Flume_Sample"), "UTF-8"); 
String combinedText = scanner.useDelimiter("\\A").next(); 
scanner.close(); // Put this call in a finally block 
String delimiter = "<?xml version=\"1.0\"?>"; 
String[] xmlFiles = combinedText.split("(?="+Pattern.quote(delimiter)+")"); 


for (int i = 0; i < xmlFiles.length; i++){ 
    File file = new File("src/main/resources/output_"+i); 
    FileWriter writer = new FileWriter(file); 
    writer.write(xmlFiles[i]); 
    System.out.println(xmlFiles[i]); 
    writer.close(); 
} 

回答

3

split方法接受一个正则表达式字符串,所以你可能需要您的分隔符String逃到一个有效的正则表达式:

String[] xmlFiles = combinedText.split(Pattern.quote(delimiter)); 

查看Pattern.quote方法。

0

请注意,如果按照这种方式进行操作,您将在内存中加载整个初始文件。 如果输入文件很大,流式处理方式会更好......

0

如果您想手动解析数据,我会使用类似的方法。

public static void parseFile(File file) throws AttributeException, LineException{ 
    BufferedReader br = null; 
    String s = ""; 
    int counter = 0; 

    if(file != null){ 
     try{ 
      br = new BufferedReader(new FileReader(file)); 
      while((s = br.readLine()) != null){ 
       if(s.contains("<?xml version='1.0'?>")){ 
        //Write in new file with Stringbuffer and Filewritter. 
       } 
      } 
      br.close(); 
      }catch (IOException e){ 
       System.out.println(e); 
      } 
    } 
}