I guess this will sound crazy, but I am reading from a file, and it seems like it skips the first line of the file.

What is going on?

Here is the source:


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

    }

It must be something I am over looking.

I copied and pasted the exact source, so I hope this happens for you also.

Thanks, caalip

有帮助吗?

解决方案

I would use FileUtils.readFileToString(file) which does this in one line.

However, when I run your code on a text file I see every line. I suspect the problem is not with your code.

其他提示

Is there a particular reason you're reading the file the way you are?

You're using parent class methods (BufferedReader has no read(CharBuffer) method, for example) and also ... the CharBuffer itself is a bit overkill. I suspect the actual problem is you're not using it correctly (usually you flip and drain Buffer objects, but I'd have to poke more to see how this ends up manipulating it)

All you need to do to read a file is:

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

This seems a bit bizarre. Try changing your try block to:

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

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

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

I haven't run this code, but give it a shot.

UPDATE: I ran your code and encountered the problem you described. I ran the code with my revision and it works.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top