Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get file size having only FileDescriptor?

Let's assume that I have a valid Java FileDescriptor which I got in this way:

FileInputStream is = new FileInputStream("/some/path/to/file.txt");
FileDescriptor fd = is.getFD();

Now please forget that I know file path. The only thing I have is a FileDescriptor. Is there a simple way to know the file size? For now I've checked that:

  1. FileDescriptor has valid() method which can tell me if it's valid but doesn't have length() or size() functionality.
  2. FileInputStream doesn't return the path and since it's a stream it obviously won't tell me the file size.
  3. File (http://docs.oracle.com/javase/7/docs/api/java/io/File.html) which has length() method doesn't have a constructor able to handle FileDescriptor.

I know that I could read whole stream and sum the length but I don't consider it as simple way.

like image 654
user1723095 Avatar asked Nov 11 '15 11:11

user1723095


1 Answers

A simple way would be to get the size of the FileChannel (refer to this question):

public long getSize(FileDescriptor fd) throws IOException {
    try (FileInputStream fis = new FileInputStream(fd)) {
        return fis.getChannel().size();
    }
}

However, as said the linked question, there is no strong guarantee that this will work for all OS.

The only sure and compatible way is to read the content of the stream, like you said in your question.

like image 162
Tunaki Avatar answered Sep 22 '22 03:09

Tunaki