首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java - Buffer -我的代码在读取时跳过TextFile的最后一行

Java - Buffer -我的代码在读取时跳过TextFile的最后一行
EN

Stack Overflow用户
提问于 2020-02-02 16:50:33
回答 1查看 15关注 0票数 0

我正在尝试将每一行上的数字的TextFile读入到ArrayList中。当我执行下面的函数时,它总是跳过最后一个元素。有人能帮帮我吗?因为我不明白这里的问题,因为它显示直到缓冲区为空,他应该在到达FileEnd时停止,对吗?

代码语言:javascript
复制
    List<Double> lines = new ArrayList<>();
    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
    StringBuilder oneLine = new StringBuilder();

    try (SeekableByteChannel byteChannel = Files.newByteChannel(Paths.get(fileName))) {

        while (byteChannel.read(buffer) > 0) {
            buffer.flip();
            for (int i = 0; i < buffer.limit(); i++) {

                char c = (char) buffer.get();

                if (c == '\r') {
                  //Skip it
                }
                if (c == '\n') {

                    System.out.println(oneLine.toString()); //Test Output to see what he got
                    lines.add(Double.parseDouble(oneLine.toString().replace(',', '.')));
                    oneLine.setLength(0);
                }
                else {
                    if (c != '\r') {
                        oneLine.append(c);
                    }
                }

            }
            buffer.clear();
        }

        System.out.println("Anzahl zeilen: " + (lines.size()));
        System.out.println("Finished");

    }
    catch (IOException e) {
        System.out.println("The File that was defined could not be found");
        e.printStackTrace();
    }

    return lines;
}

每行一个数字的TextFile:

代码语言:javascript
复制
999973
22423
999974
999975
999976
999977
573643
999978
999979
999980
999981
34322
999982
999983
999984
999985
999986
999987
999988
3
67
84,000
7896575543
8.0
100001
9999991
8.0
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-02 17:08:40

当到达文件末尾并且文件末尾没有换行符时,可以将字符添加到StringBuilder中,但不会将其附加到列表中。您可以在文本文件的末尾添加换行符,也可以在调用buffer.clear()之前调用lines.add(...)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60024531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档