【问题标题】:how to split one text into multiple text files如何将一个文本拆分为多个文本文件
【发布时间】:2018-03-29 20:07:52
【问题描述】:

我有以下文字:

1
(some text)
   /
2
(some text)
       /
.
.
    /
8519
(some text)

我想把这个文本分成几个文本文件,每个文件在文本之前都有数字的名称,即(1.txt2.txt)等等,这个文件的内容将是文本。

我试过这段代码

BufferedReader br = new BufferedReader(new FileReader("(Path)\\doc.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();
    while (line != null) {
        sb.append(line);
        // sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String str = sb.toString();
    String[] arrOfStr = str.split("/");
    for (int i = 0; i < arrOfStr.length; i++) {
        PrintWriter writer = new PrintWriter("(Path)" + arrOfStr[i].charAt(0) + ".txt", "UTF-8");
        writer.println(arrOfStr[i].substring(1));
        writer.close();
    }
    System.out.println("Done");
} finally {
    br.close();
}

此代码适用于文件 1-9。但是,文件 10-8519 出现问题,因为我在字符串中取了第一个数字 (arrOfStr [i].charAt(0)) 我知道我的解决方案不够有任何建议吗?

【问题讨论】:

  • 您应该搜索从字符串中提取数字或在第一个数字之后使用正则表达式执行子字符串。如果您的文本非常一致,即数组中的每个条目都有一个前导数字,您甚至可以在第一个“空格”处执行一个子字符串:yourNumber = arrOfStr[i].substring(0, arrOfStr[i].indexOf (" "));
  • 我很惊讶您的 StringBuilder 或 arrOfStr 没有弹出。我会首先重写,就像你之前尝试的那样,在你阅读它们时处理它们。您也知道您的问题 - 您只查看 1 个字符 char(0)
  • @CopyJoshthanx 为您的回答...这会很棒,但是当我拆分文本时,数字和第一个字符串之间没有空格,因此它将数字+第一个单词作为 yourNumber

标签: java file


【解决方案1】:

除了我的评论,考虑到前导整数和第一个单词之间没有空格,第一个空格的子字符串不起作用。

这个问题/答案有几个选项应该会有所帮助,使用正则表达式 (\d+) 的选项是最简单的一个 imo,并在下面复制。

Matcher matcher = Pattern.compile("\\d+").matcher(arrOfStr[i]);
matcher.find();
int yourNumber = Integer.valueOf(matcher.group());

Given a string find the first embedded occurrence of an integer

【讨论】:

    【解决方案2】:

    正如你所提到的,问题是你只取第一个数字。您可以枚举第一个字符,直到找到非数字字符 (arrOfStr[i].charAt(j) &lt;'0' || arrOfStr[i].charAt(j) &gt; '9'),但使用 Scanner 和适当的正则表达式应该更容易。

    int index = new Scanner(arrOfStr[i]).useDelimiter("\\D+").nextInt();
    

    分隔符正好是任意一组非数字字符

    【讨论】:

      【解决方案3】:
      Here is a quick solution for the given problem. You can test and do proper exception handling.
      
      package practice;
      
      import java.io.IOException;
      import java.nio.file.Files;
      import java.nio.file.Path;
      import java.nio.file.Paths;
      import java.nio.file.StandardOpenOption;
      import java.util.List;
      
      public class FileNioTest {
      
          public static void main(String[] args) {
      
              Path path = Paths.get("C:/Temp/readme.txt");
      
              try {
                  List<String> contents = Files.readAllLines(path);
                  StringBuffer sb = new StringBuffer();
                  String folderName = "C:/Temp/";
                  String fileName = null;
                  String previousFileName = null;
      
                  // Read from the stream
                  for (String content : contents) {// for each line of content in contents
                      if (content.matches("-?\\d+")) {  // check if it is a number (based on your requirement) 
                          fileName = folderName + content + ".txt";   // create a file name with path
                          if (sb != null && sb.length() > 0) {  // this means if content present to write in the file
                              writeToFile(previousFileName, sb);  // write to file
                              sb.setLength(0);              // clearing buffer
                          }
                          createFile(fileName);           // create a new file if number found in the line
                          previousFileName = fileName;    // store the name to write content in previous opened file. 
                      } else {
                          sb.append(content);             // keep storing the content to write in the file.
                      }
                      System.out.println(content);// print the line
                  }
                  if (sb != null && sb.length() > 0) {
                      writeToFile(fileName, sb);
                      sb.setLength(0);
                  }
              } catch (IOException ex) {
                  ex.printStackTrace();// handle exception here
              }
          }
      
          private static void createFile (String fileName) {
              Path newFilePath = Paths.get(fileName);
      
              if (!Files.exists(newFilePath)) {
                  try {
                      Files.createFile(newFilePath);
                  } catch (IOException e) {
                      System.err.println(e);
                  }
              }
          }
      
          private static void writeToFile (String fileName, StringBuffer sb) {
              try {
                  Files.write(Paths.get(fileName), sb.toString().getBytes(), StandardOpenOption.APPEND);
              }catch (IOException e) {
                   System.err.println(e);
              }
          }
      
      }
      

      【讨论】:

      • 看起来您的答案将在文本文件中包含分隔符“//”,并且由于它不检查它,因此行有一个数字但没有用 // 分隔的情况仍然会错误地创建文件
      • 并非如此。使用@Abeer 给出的每行具有编号的文件进行测试。 1 这是第一个文件 2 这是第二个文件 这是第二个文件 3 这是第三个文件 这是第三个文件 这是第三个文件 4 这是第四个文件 这是第四个文件 这是第四个文件 这是第四个文件 5这是第五个文件 这是第五档 这是第五档 这是第五档 这是第五档 6 7 8 9 这是第九档 这是第九档 这是第九档 这是第九档 这是第九档 这是第九档 这是第九档 这是第九档file 这是第九个文件
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多