文件拆分并写入多个文件

你能帮我解决这个问题吗?考虑以下,它在单个文本文件中说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)

如何将上面的一个分成两个文件。意思是从 (AP900) 到 (NNNN) 从第 1 行到第 9 行转到one.txt和从 (AP900) 到 (NNNN) 从第 11 行到第 19 行转到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");

        }


慕妹3242003
浏览 147回答 1
1回答

哆啦的时光机

你的描述不清楚,有些要求看起来很奇怪(你为什么要创建像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() */) {&nbsp; &nbsp; String line = lines.next();&nbsp; &nbsp; Matcher startMatcher = start.matcher(line);&nbsp; &nbsp; if (startMatcher.find()) {&nbsp; &nbsp; &nbsp; &nbsp; reading = true;&nbsp; &nbsp; &nbsp; &nbsp; fos = new FileOutputStream(String.valueOf(i++) + ".txt"/*fileNames.next()*/);&nbsp; &nbsp; }&nbsp; &nbsp; if (reading) {&nbsp; &nbsp; &nbsp; &nbsp; fos.write(line.getBytes(StandardCharsets.UTF_8));&nbsp; &nbsp; &nbsp; &nbsp; fos.write('\n');&nbsp; &nbsp; }&nbsp; &nbsp; Matcher endMatcher = end.matcher(line);&nbsp; &nbsp; if (endMatcher.find()) {&nbsp; &nbsp; &nbsp; &nbsp; if (fos != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fos.close();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; reading = false;&nbsp; &nbsp; }}if (fos != null) {&nbsp; &nbsp; fos.close();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java