如何将一个文本拆分成多个文本文件

时间:2018-03-29 20:07:53

标签: java file

我有以下文字:

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。但是,由于我在字符串中使用了第一个数字(arrOfStr [i].charAt(0)),因此文件10-8519出了问题。我知道我的解决方案不足以提出任何建议吗?

3 个答案:

答案 0 :(得分:1)

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

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

var winLoss = _teamService.GetGames()
.Where(x => x.Result != "Tie").GroupBy(x => x.Result);

var win =  winLoss.Select(x => x.Count(a => a.Result == "Hello")).FirstOrDefault();
var loose =  winLoss.Select(x => x.Count(a => a.Result != "Hello")).FirstOrDefault();

Given a string find the first embedded occurrence of an integer

答案 1 :(得分:0)

正如您所提到的,问题是您只取第一个数字。您可以枚举第一个字符,直到找到非数字字符(arrOfStr[i].charAt(j) <'0' || arrOfStr[i].charAt(j) > '9'),但是使用扫描仪和适当的正则表达式会更容易。

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

分隔符恰好是任何非数字字符组

答案 2 :(得分:0)

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

}