FileChannel#size()


I recently wrote a method which uses FileChannel#size() internally.

public static void doSomethingLikeABoss(final FileChannel channel)
    throws IOException {

    final long size = channel.size();
    // TODO: find the reason why the size is always 0L.
}

And I found that the size() always returns 0L. The problem was the way I creating FileChannel instances with a given File. I used FileInputStream#getChannel() which seems lost information about the file.

public static void doSomethingLikeABoss(final File file)
    throws IOException {

    // open channels like a boss!
    try (final FileChannel channel = new FileInputStream(file).getChannel()) {
        doSomethingLikeABoss(channel);
    }
}

I had to use the new method introduced with Java 1.7 .

public static void doSomethingLikeABoss(final File file)
    throws IOException {

    // open channels like a REAL boss!
    try (final FileChannel channel = FileChannel.open(file.toPath())) {
        doSomethingLikeABoss(channel);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s