273286078

导航

 

遍历文件夹里的文件,将包含多个<REC>的文件拆成若干只包含一个<REC>的文件

package com.prepub;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class SplitRecCase {

    public static void makeRecFile(String opath01)      //将包含多个<REC>的文件拆成若干只包含一个<REC>的文件
    {
        try {
            FileInputStream fis = new FileInputStream(opath01);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);

            String temp;
            File f01 = new File(opath01);
            String dir = f01.getParent()+"rec";
            File fr = new File(dir);
//            String filename = f01.getName().split("\\.")[0];    
            FileOutputStream fos =null;
            OutputStreamWriter osw=null;
            BufferedWriter bw =null;
            
            if(!fr.exists())
            {
                fr.mkdirs();
            }
            
            int i = 0;
            String npath02 = dir+"\\1.txt";
            while((temp = br.readLine())!=null)      //按行读文件
            {
                if(temp.contains("<REC>")){
                    i++;
                    npath02 = dir+"\\"+f01.getName().split("\\.")[0]+"_"+i+".txt";
                    fos = new FileOutputStream(npath02);
                    osw = new OutputStreamWriter (fos);
                    bw = new BufferedWriter(osw);
                    bw.write(temp);
                    bw.newLine();
                    bw.flush();
                }else{
                    bw.write(temp);
                    bw.newLine();
                    bw.flush();                    
                    }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String opath01 = null ;
        String path = "E:\\data";
        File of = new File(path);
        if(of.isDirectory())
        {
            File[] files = of.listFiles();
            for(File f: files)        //遍历文件夹里的文件
            {
                System.out.println(f.getAbsolutePath());
                opath01 = f.getAbsolutePath();
                makeRecFile(opath01);    
            }
            System.out.println("完成");
        }else{
            makeRecFile(of.getAbsolutePath());
        }    
    }

}

 

posted on 2017-10-30 19:27  273286078  阅读(507)  评论(0编辑  收藏  举报