繁体   English   中英

为什么使用 BufferedReader 读取文件注释的第一行?

[英]Why is the first line of a file note read with BufferedReader?

我想这听起来很疯狂,但我正在从一个文件中读取,它似乎跳过了文件的第一行。

到底是怎么回事?

这是来源:


    private void loadFile(String fileNPath)
    {
        StringBuilder currentFileContents = new StringBuilder();
        CharBuffer contentsBuffer = CharBuffer.allocate(65536);

        int status=0;
        try
        {
            BufferedReader in = new BufferedReader(new FileReader(fileNPath));

            while(status!=-1)
            {
                status=in.read(contentsBuffer);
                currentFileContents.append(contentsBuffer);
                contentsBuffer.clear();
            }

            System.out.println(currentFileContents.toString());
        }
        catch(FileNotFoundException n)
        {
            //Should be imposible
        }
        catch(IOException n)
        {
            n.printStackTrace(System.out);
        }

    }

这一定是我在看的东西。

我复制并粘贴了确切的来源,所以我希望这也发生在你身上。

谢谢,卡利普

您以自己的方式阅读文件是否有特殊原因?

您正在使用父 class 方法(例如BufferedReader没有read(CharBuffer)方法),而且...... CharBuffer本身有点矫枉过正。 我怀疑实际的问题是你没有正确使用它(通常你会翻转和排出 Buffer 对象,但我必须多戳才能看到它最终是如何操纵它的)

读取文件所需要做的就是:

StringBuilder currentFileContents = new StringBuilder();
try
{
    BufferedReader in = new BufferedReader(new FileReader(fileNPath));
    String line = null;
    while( (line = in.readline()) != null )
    {
        currentFileContents.append(line);
    }

    System.out.println(currentFileContents.toString());
}
catch(FileNotFoundException n)
{
    //Should be imposible
}
catch(IOException n)
{
    n.printStackTrace(System.out);
}

这似乎有点奇怪。 尝试将您的 try 块更改为:

try
    {
        BufferedReader in = new BufferedReader(new FileReader(fileNPath));

        status=in.read(contentsBuffer.array(), 0, 65536);
        currentFileContents.append(contentsBuffer);

        System.out.println(currentFileContents.toString());
    }

我没有运行此代码,但试一试。

更新:我运行了您的代码并遇到了您描述的问题。 我用我的修订版运行了代码,它可以工作。

我会使用 FileUtils。 readFileToString (file) 在一行中执行此操作。

但是,当我在文本文件上运行您的代码时,我会看到每一行。 我怀疑问题不在于您的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM