文件分割并写入多个文件

时间:2018-09-23 06:16:44

标签: java java-8 apache-camel

能否请您帮忙。考虑跟随,它在单个文本文件中说chines.txt

line no:1(AP9000)
2<CAT-DOG FILE>
3<DATA>
4<DATE=19NOV14>
5GOOG2402l 19NOV14 05:00 2.0
6APL2402h  19NOV14 05:00 6.0
7IBM2401w  19NOV14 05:00 586.0
8<END>
Line no: 9 (NNNN)
Line number:10    
11(AP9000)
12<CAT-DOG FILE>
13<DATA>
14<DATE=19NOV14>
15GOOG2402l 19NOV14 05:00 2.0
16APL2402h  19NOV14 05:00 6.0
17IBM2401w  19NOV14 05:00 586.0
18<END>
19(NNNN)

如何将以上内容拆分为两个文件。从第1行到第9行从(AP900)到(NNNN)进入one.txt,从第11行到第19行从(AP900)到(NNNN)进入two.txt。例如,将行号指定为1谷19。

如何将Java 8或Apache Camel分成两个文件?

读取该文件的Java 8代码

try {

       List<String> stringList =Files.lines(Paths.get("chines.txt"))
                     .collect(Collectors.toList());
                stringList.forEach(x -> System.out.println(x));
    }catch (Exception e){
        System.out.println("Could not found file");
        }

1 个答案:

答案 0 :(得分:0)

您的描述不清楚,有些要求似乎很奇怪(为什么要创建类似one.txt而不是1.txt的文件)?但这只是一个小的手指练习。也许可以帮上忙吗?

// Iterator<String> fileNames = Arrays.asList("one.txt", "two.txt", "three.txt", "four.txt", "five.txt", "six.txt", "seven.txt").iterator();
int i = 1;
Pattern start = Pattern.compile("\\(AP9000\\)");
Pattern end = Pattern.compile("\\(NNNN\\)");
boolean reading = false;
FileOutputStream fos = null;
Iterator<String> lines = Files.lines(Paths.get("c:/d/test.txt")).iterator();
while (lines.hasNext() /* && fileNames.hasNext() */) {
    String line = lines.next();
    Matcher startMatcher = start.matcher(line);
    if (startMatcher.find()) {
        reading = true;
        fos = new FileOutputStream(String.valueOf(i++) + ".txt"/*fileNames.next()*/);
    }
    if (reading) {
        fos.write(line.getBytes(StandardCharsets.UTF_8));
        fos.write('\n');
    }
    Matcher endMatcher = end.matcher(line);
    if (endMatcher.find()) {
        if (fos != null) {
            fos.close();
        }
        reading = false;
    }
}
if (fos != null) {
    fos.close();
}