How to use Java Path Interface

0
1367

Java 8 has a Path interface which comes very handy when we need to parse through a file or some path of an entity to build other objects.

Path interface has some useful methods like:

  • int getNameCount() – Returns the number of name elements in the path.
  • getParent(), getRoot(),
  • Path resolve(String path)
  • Path toAbsolutePath()

The standard imports:

    import java.nio.file.Path;
    import java.nio.file.Paths;

This can be best explained with an example use-case.

Example requirement:

A business has digital assets (files) that have Tags on each of them. And these Tags as in a hierarchy. Like

  • Asset 1: Tags
    • SuperCategory: Talk
    • Category: Kids
    • Channel: Kids Place
    • Show: Back to School

Some Assets may not have all the levels of tags. We need to build a search service that should return 4 lists (SuperCategory, Category, Channel, Show) and put Assets in each of these.

For each asset, if the tag is marked, they are saved as a Path. Like /etc/tags/namespace/super-category/category/channel/show/show-name

Solution

Since the value being saved for each Asset is like a Path, we can use Java Path, break it down, see until what level the Tag is marked for each file.

For example:

  • Asset 1: /etc/tags/namespace/shows/talk/kids/kids-place/back-to-school
  • Asset 2: /etc/tags/namespace/shows/entertainment
  • Asset 3: /etc/tags/namespace/shows/religion/family-talk

i know this is weird but there was such a requirement

Sample code

Note: Please contact me for full code.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here