Appendix A. Java IO to EntityFS and back again

Table of Contents

From File to entity
From entity to File

An application often has to deal with both EntityFS entities and plain, old Java IO File:s[5]. This appendix shows how you can move between the two worlds with the least effort.

Depending on what the File should be used for, there are several methods available that can represent it as an EntityFS entity.

1. Create a file-based FileSystem on the File

This method gives most flexibility in configuring how the desired entities should behave, but it is perhaps also the method requiring the most effort to use.

Example A.1. Creating a custom file system on the File

// f is a file File called f

// Create a read/write file system on the file's parent directory.
FileSystem fs = new FSRWFileSystemBuilder().
  setRoot(f.getParentFile()).
  create();
  
// This is the file, represented as a file entity
EFile ef = Directories.getFile(fs.getRootDirectory(), "f");

2. Use FileSystems to create a FileSystem on the File

The utility class FileSystems has the getEntityForDirectory and getEntityForFile shortcut methods for creating file systems on File objects.

Example A.2. Creating a file system on the File using a FileSystems method

// f is a file File called f

// The returned EFile entity is in a file system created using the default
// settings of FSRWFileSystemBuilder
EFile ef = FileSystems.getEntityForFile(f, false);

3. Use FSCFileResolvableUtil to get an entity in an existing FileSystem

If the File references a location in an existing FileSystem, the FSCFileResolvableUtil methods getEntityForFile or getEntityLocationForFile can be used to retrieve the referenced Entity.

Example A.3. Getting an existing Entity using a FSCFileResolvableUtil method

// f is a file File that references the file entity /d/f in the file
// system fs.

EFile ef = (EFile) FSCFileResolvableUtil.getEntityForFile(fs, f);

4. Use an adapter object to adapt the File to the desired interface

A File can be adapted different interfaces using an adapter object.


Example A.4. Adapting a File to the ReadableFile interface

// f is a File containing text

// Use the Files utility class to read the contents of the text file
// to a String
String s = Files.readTextFile(new FileReadableFile(f));

Conversions from entity objects to File objects can be useful when working with API:s that use File arguments. File objects can be created for an entities in a file system that is FSCFileResolvable using the FSCFileResolvableUtil method getFileForEntity.




[5] POJIOFS?