FSPath API

The FSPath API offers a simple yet powerful, concise yet extensible way of doing every day tasks with the filesystem.

Finding files

The basis of all FSPath interactions is the FSPath query:

  FSPath fspath = FSPathFactory.newFSPath();
  
  FSPathResultsList results = fspath.query("//file[@name = 'error.log']");

Deleting files

Retrieving a list of files is fairly straightforward, but what else can the API do ?

Well the key is with the FSPathResultList, it is this object where the copy(), delete(), rename() and move() methods are found.

This enables those methods to be 'chained' onto the end of the query() method like so :

  results = fspath.query("//file[@name = 'error.log']").delete();

The above statement would delete all files found by the query.

Copying files

Similarly, to copy files :

  String destPath = "/var/tmp"; //the folder to copy to
  results = fspath.query("//file[@name = 'error.log']").copy(destPath);

Renaming files

Renaming files works in much the same way, however there are some additional things to think about. If there are many results returned by the query, how can you rename each file without doing it individually ?

Well, FSPath provides a mechanism to rename files based on regex pattern replacement.

As an example, imagine we had a directory full of log files which had the following format

  applog-01_01_2007.log.1
  applog-01_01_2007.log.2
  ...

But our log file viewer will only read files ending in .log and not .log.2 (a little contrived, but it happens;)

So we want to rename all the files so they look like this :

  applog-01_01_2007_1.log
  applog-01_01_2007_2.log
  ...

To achieve this we just need 3 things, an FSPath query to locate the files, a regex pattern to match the filenames and a replace expression to rename them with.

  fspath.query("dir[@name = 'logs']/file")
        .rename("(.*)\\.log\\.([0-9]+)", "$1_$2.log");

So here we locate all files contained in directory named 'logs' and specify a regular expression with two capturing groups, one being everything up to the '.log' in the filename, and the other being the number after the ".log." . The replace expression simply specifies that the new file name will have the text in the first capturing group, followed by a "_" then the text in the second capturing group and then ".log".

Moving Files

Move works in the same way to copy() except that the original files are deleted afterwards.