3

How can I obtain the filename from a opened RandomAccessFile instance?

I can find only the following methods related to the file itself:

  • getFD() : which returns a FileDescriptor object
  • getChannel() : which returns a FileChannel object

I would like to get a File class instance or also directly the filename string that I pass to the constructor of RandomAccessFile:

RandomAccessFile(File file, String mode) 

Thanks!

alexroat
  • 1,687
  • 3
  • 23
  • 34
  • 3
    Retain the file that you use to open the RAF. I would never depend on RAF or pass it around in any of my interfaces anyway - it is an implementation detail. If you have interface Foo, that does something, you should have a FileBasedFoo implementation. Keep the File as a member variable for later reference. – Doug Moscrop Nov 21 '11 at 17:41
  • Your only option is probably to write some very ugly and contrived code that passes the file descriptor to JNI and uses C code to find the file associated to the file descriptor. – Tudor Nov 21 '11 at 18:01

1 Answers1

2

I'm adding my comment (above) as an answer for your consideration/voting (me want reputation!)

The usage of a RandomAccessFile should be perceived as an implementation detail. Don't pass it around your code. You may soon find you want things that previously depended on the RAF to work with something else - maybe a remote system. Take the business logic / behavior out of what you're doing and put it in an interface. Implement that interface in a class that stores the File and the RandomAcecssFile as member variables. This ensures you always have access to both. You could maybe even use a URI - which File takes as a constructor parameter. This is a pretty open and reasonable thing - so if you have an interface Foo:

interface Foo {
    public URI getUri();

    public void doSomething();

    public Bar doSomethingElse();
}

You can have a:

class FileBasedFoo implements Foo {
    private File file;
    private RandomAccessFile raf;

    // ... your impl here
}

and anywhere in your code, where you've used a Foo, can now transparently switch to..

class RpcFoo implements Foo {
    // ... some SOAPy implementation here
}

class RestFoo implements Foo {
    // ... you get the idea
}
Doug Moscrop
  • 4,479
  • 3
  • 26
  • 46