Java 按特定字符序列将文本文件拆分为多个文件

Java 按特定字符序列将文本文件拆分为多个文件,java,text,split,bufferedreader,stringbuilder,Java,Text,Split,Bufferedreader,Stringbuilder,我有一个以下格式的文件 .I 1 .T experimental investigation of the aerodynamics of a wing in a slipstream . 1989 .A brenckman,m. .B experimental investigation of the aerodynamics of a wing in a slipstream . .I 2 .T simple shear flow past a flat plate in an incomp

我有一个以下格式的文件

.I 1
.T
experimental investigation of the aerodynamics of a
wing in a slipstream . 1989
.A
brenckman,m.
.B
experimental investigation of the aerodynamics of a
wing in a slipstream .
.I 2
.T
simple shear flow past a flat plate in an incompressible fluid of small
viscosity .
.A
ting-yili
.B
some texts...
some more text....
.I 3
...
.i1”表示与文档ID1对应的文本块的开头,“.i2”表示与文档ID2对应的文本块的开头

我需要的是读取“.I 1”和“.I 2”之间的文本,并将其保存为单独的文件,如“DOC_ID_1.txt”,然后读取“.I 2”和“.I 3”之间的文本 并将其另存为单独的文件,如“DOC_ID_2.txt”等。假设.I#的数量未知

我已经试过了,但没法完成。任何帮助都将不胜感激

String inputDocFile="C:\\Dropbox\\Data\\cran.all.1400";     
try {
     File inputFile = new File(inputDocFile);
     FileReader fileReader = new FileReader(inputFile);
     BufferedReader bufferedReader = new BufferedReader(fileReader);
     String line=null;
     String outputDocFileSeperatedByID="DOC_ID_";
     //Pattern docHeaderPattern = Pattern.compile(".I ", Pattern.MULTILINE | Pattern.COMMENTS);
     ArrayList<ArrayList<String>> result = new ArrayList<> ();
     int docID =0;
     try {
          StringBuilder sb = new StringBuilder();
          line = bufferedReader.readLine();
          while (line != null) {
              if (line.startsWith(".I"))
              { 
                 result.add(new ArrayList<String>());
                 result.get(docID).add(".I");
                 line = bufferedReader.readLine();

                 while(line != null && !line.startsWith(".I")){
                    line = bufferedReader.readLine();
                    }
                     ++docID;
              }        
              else line = bufferedReader.readLine();
          }

      } finally {
          bufferedReader.close();
      }
   } catch (IOException ex) {
      Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
   }
String inputDocFile=“C:\\Dropbox\\Data\\cran.all.1400”;
试一试{
文件inputFile=新文件(inputDocFile);
FileReader FileReader=新的FileReader(inputFile);
BufferedReader BufferedReader=新的BufferedReader(文件阅读器);
字符串行=null;
字符串outputDocFileSeperatedByID=“DOC\u ID”;
//Pattern-docHeaderPattern=Pattern.compile(“.I”,Pattern.MULTILINE | Pattern.COMMENTS);
ArrayList结果=新的ArrayList();
int-docID=0;
试一试{
StringBuilder sb=新的StringBuilder();
line=bufferedReader.readLine();
while(行!=null){
if(第行开始时带(“.I”))
{ 
添加(新的ArrayList());
结果.get(docID).add(“.I”);
line=bufferedReader.readLine();
while(line!=null&&!line.startsWith(“.I”)){
line=bufferedReader.readLine();
}
++docID;
}        
else line=bufferedReader.readLine();
}
}最后{
bufferedReader.close();
}
}捕获(IOEX异常){
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE,null,ex);
}

查找正则表达式,Java为此内置了库

这些链接将为您提供一个起点,您可以有效地使用计数器对字符串执行模式匹配,并存储第一个模式匹配和第二个模式匹配之间的任何内容。可以使用Formatter类将此信息输出到单独的文件中

可在此处找到:-

查找正则表达式,Java为此内置了库

这些链接将为您提供一个起点,您可以有效地使用计数器对字符串执行模式匹配,并存储第一个模式匹配和第二个模式匹配之间的任何内容。可以使用Formatter类将此信息输出到单独的文件中

可在此处找到:-

查找正则表达式,Java为此内置了库

这些链接将为您提供一个起点,您可以有效地使用计数器对字符串执行模式匹配,并存储第一个模式匹配和第二个模式匹配之间的任何内容。可以使用Formatter类将此信息输出到单独的文件中

可在此处找到:-

查找正则表达式,Java为此内置了库

这些链接将为您提供一个起点,您可以有效地使用计数器对字符串执行模式匹配,并存储第一个模式匹配和第二个模式匹配之间的任何内容。可以使用Formatter类将此信息输出到单独的文件中

可在此处找到:-

您想找到与“in”匹配的行

您需要的正则表达式是:
^.I\d$

  • ^
    表示行的开头。因此,如果在
    I
    之前有一些空格或文本,则该行将与正则表达式不匹配
  • \d
    表示任何数字。为了简单起见,我只允许这个正则表达式中有一个数字
  • $
    表示行的结尾。因此,如果数字后面有一些字符,则该行将与表达式不匹配
现在,您需要逐行读取文件,并保留对写入当前行的文件的引用

使用
Files.lines(),在Java8中逐行读取文件要容易得多

<强>注释< /强>:为了提取数字,我使用原始<代码>“.Sub())/代码>,我认为它是邪恶的,但更容易理解。您可以使用

模式
匹配器
以更好的方式进行匹配:

使用此正则表达式:“
.I(\\d)
”。(与前面相同,但带有括号,表示要捕获的内容)。然后:


您要查找与“in”匹配的行

您需要的正则表达式是:
^.I\d$

  • ^
    表示行的开头。因此,如果在
    I
    之前有一些空格或文本,则该行将与正则表达式不匹配
  • \d
    表示任何数字。为了简单起见,我只允许这个正则表达式中有一个数字
  • $
    表示行的结尾。因此,如果数字后面有一些字符,则该行将与表达式不匹配
现在,您需要逐行读取文件,并保留对写入当前行的文件的引用

使用
Files.lines(),在Java8中逐行读取文件要容易得多

<强>注释< /强>:为了提取数字,我使用原始<代码>“.Sub())/代码>,我认为它是邪恶的,但更容易理解。您可以使用

模式
匹配器
以更好的方式进行匹配:

使用此正则表达式:“
.I(\\d)
”。(与前面相同,但带有括号,表示要捕获的内容)。然后:


您要查找与“in”匹配的行

您需要的正则表达式是:
^.I\d$

  • ^
    表示行的开头。因此,如果存在一些空白或
    private String currentFile = "root.txt";
    
    public static final String REGEX = "^.I \\d$";
    
    public void foo() throws Exception{
    
      Path path = Paths.get("path/to/your/input/file.txt");
      Files.lines(path).forEach(line -> {
        if(line.matches(REGEX)) {
          //Extract the digit and update currentFile
          currentFile = "File DOC_ID_"+line.substring(3, line.length())+".txt";
          System.out.println("Current file is now : currentFile);
        } else {
          System.out.println("Writing this line to "+currentFile + " :" + line);
          //Files.write(...);
        }
      });
    
    Pattern pattern = Pattern.compile(".I (\\d)");
    Matcher matcher = pattern.matcher(".I 3");
    if(matcher.find()) {
      System.out.println(matcher.group(1));//display "3"
    }
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    public class Test {
    
        /**
         * @param args
         * @throws IOException 
         */
        public static void main(String[] args) throws IOException {
            // TODO Auto-generated method stub
            String inputFile="C:\\logs\\test.txt"; 
             BufferedReader br = new BufferedReader(new FileReader(new File(inputFile)));
             String line=null;
             StringBuilder sb = new StringBuilder();
             int count=1;
            try {
                while((line = br.readLine()) != null){
                    if(line.startsWith(".I")){
                        if(sb.length()!=0){
                            File file = new File("C:\\logs\\DOC_ID_"+count+".txt");
                            PrintWriter writer = new PrintWriter(file, "UTF-8");
                            writer.println(sb.toString());
                            writer.close();
                            sb.delete(0, sb.length());
                            count++;
                        }
                        continue;
                    }
                    sb.append(line);
                }
    
               } catch (Exception ex) {
                 ex.printStackTrace();
               }
               finally {
                      br.close();
    
                  }
        }
    
    }