Java stream 并发应用案例

在磁盘目录下有几十个txt文件,里面存储着XML格式的数据,每个文件在2-3M左右,现在需要将以上文件解析出来保存到mysql数据库,总数据量大概在30万条左右。

(1)首先通过stream并发解析TXT文件,然后将解析的结果按照LOAD DATA的标准全部保存到一个文件中;

    public static void t02(){
        long startTime = System.currentTimeMillis();
        
        //获取目录下的文件路径
        String basePath  = "G:/tmp/loaddatatest";
        
        File filePath = new File(basePath);
        
        File[] files = filePath.listFiles();
        
        List<File> fileList = Arrays.asList(files);
        
        
        fileList.stream().parallel().forEach(file -> {
            try {
                SAXReader saxReader = new SAXReader();
                Document doc = saxReader.read(file);
                
                Element dataEle = doc.getRootElement();
                
                Element list2Ele = dataEle.element("LIST2");
                
                List<Element> itemEles = list2Ele.elements("item");
                
                StringBuilder sb = new StringBuilder();
                
                for (Element ele : itemEles) {
                    String t1= ele.elementText("t1");
                    //此处字段省略...
                    sb.append(t1).append(",")   
                      .append(t2)......append("\r\n");
                }
                
                FileUtils.writeStringToFile(new File("G:/tmp/loaddatatest/00.txt"), sb.toString(), "UTF-8", true);
            } catch (DocumentException ex) {
                Logger.getLogger(T03.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(T03.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
        
        
        
        long endTime = System.currentTimeMillis();
        
        System.out.println("解析XML耗时:"+(endTime-startTime)+"ms");
    }

(2)步骤(1)执行完成后,通过调用提前编写好的SHELL脚本将结果文件导入到mysql数据库;

参照《https://www.cnblogs.com/yshyee/p/11826416.html》。

(3)通过以上方式,全流程执行完成在8秒左右。

猜你喜欢

转载自www.cnblogs.com/yshyee/p/11826473.html
今日推荐