【问题标题】:Splitting a text file into multiple files by specific character sequence按特定字符序列将文本文件拆分为多个文件
【发布时间】:2015-08-01 11:21:09
【问题描述】:

我有一个格式如下的文件。

.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
...

.I 1”表示与doc ID1和“.I 2" 表示 doc 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);
   }

【问题讨论】:

  • 注意:您正在使用老式的方式逐行读取文件。今天,Files.lines() 给你一个Stream&lt;String&gt;。然后,正则表达式将帮助您找到I \d。最后,使用Files.write() 以便轻松写入相应的文件。
  • Arnaud Denoyelle 感谢您的提示。

标签: java text split bufferedreader stringbuilder


【解决方案1】:

你想找到匹配“I n”的行。

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

  • ^ 表示行首。因此,如果I 之前有一些空格或文本,则该行将与正则表达式不匹配。
  • \d 表示任何数字。为了简单起见,我在这个正则表达式中只允许一个数字。
  • $ 表示行尾。因此,如果数字后面有一些字符,则该行将与表达式不匹配。

现在,您需要逐行读取文件并保留对您写入当前行的文件的引用。

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

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(...);
    }
  });

注意:为了提取数字,我使用了原始的"".substring(),我认为它是邪恶的,但更容易理解。您可以使用PatternMatcher 以更好的方式做到这一点:

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

Pattern pattern = Pattern.compile(".I (\\d)");
Matcher matcher = pattern.matcher(".I 3");
if(matcher.find()) {
  System.out.println(matcher.group(1));//display "3"
}

【讨论】:

  • 一个更好的方法,我做到了。
  • 使用您的建议后,当我尝试将“行”写入文件时,它无法正常工作,有些文件是空的,有些文件包含所有输入文件。这是我添加到您的代码中的写作部分:
【解决方案2】:

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

https://docs.oracle.com/javase/tutorial/essential/regex/

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

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

在这里找到:- http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

【讨论】:

    【解决方案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();
    
                  }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多