DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • APIs for Logistics Orchestration: Designing for Compliance, Exceptions, and Edge Cases
  • Building Data Pipelines With Jira API

Trending

  • Scalability 101: How to Build, Measure, and Improve It
  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • How to Format Articles for DZone
  1. DZone
  2. Data Engineering
  3. Databases
  4. Getting to Know java.nio.file.Path (Part 1)

Getting to Know java.nio.file.Path (Part 1)

Java 9 will be introducing a number of enhancements to the File API. Let's run through most of them and see how they'll simplify your work.

By 
Mohamed Sanaulla user avatar
Mohamed Sanaulla
·
Aug. 21, 17 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
19.2K Views

Join the DZone community and get the full member experience.

Join For Free

The last few releases of Java, namely Java 7, Java 8, and the upcoming Java 9, have quite a lot of features to make the lives of Java developers easier. (I know Java 9 will make it tougher, but only while you adopt the new paradigm. After that, it’s going to be much better).

One of the new features is the enhancement of the File API introduced in Java 7. One of the new classes of that feature set is java.nio.file.Path and its factory java.nio.file.Paths.

Maven Dependencies

We will be using JUnit and AssertJ to write our tests to demonstrate the API.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <!-- use 2.8.0 for Java 7 projects -->
    <version>3.8.0</version>
    <scope>test</scope>
</dependency>


Creating an Instance of java.nio.file.Path

As I mentioned before, java.nio.file.Paths is the creator for java.nio.file.Path. It provides two factory methods:

  • static Path get(String first, String … more)
  • static Path get(URI uri)

Those can be used to get an instance of java.nio.file.Path. Let us look at the two ways to obtain the instance:

@Test
public void testPathCreation(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.isAbsolute()).isFalse();
    assertThat(path.toString()).isEqualTo("src\\main\\resources");

    Path uriPath = Paths.get(URI.create("file:///Users/Mohamed/git"));
    assertThat(uriPath.isAbsolute()).isFalse();
    assertThat(uriPath.toAbsolutePath().toString())
            .isEqualTo("C:\\Users\\Mohamed\\git");
}


Exploring the APIs

Using endsWith()

This method is used to check if a given Path object ends with another Path object or a path represented as a String object.

@Test
public void testEndsWith(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.endsWith(Paths.get("main","resources"))).isTrue();
    assertThat(path.endsWith("resources")).isTrue();
}


Using getFileName()

This method returns the name of the directory or the file present at the terminal or end of the path.

@Test
public void testGetFileName(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getFileName().toString()).isEqualTo("resources");
    path = Paths.get("src", "test", "java", "info", 
        "sanaulla","PathDemoTest.java");
    assertThat(path.getFileName().toString())
        .isEqualTo("PathDemoTest.java");
}


Using getFileSystem()

This method returns an instance of java.nio.file.FileSystem representing the underlying file system. We will look at this in detail in a future post.

@Test
public void testGetFileSystem(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getFileSystem()).isNotNull();
    assertThat(path.getFileSystem().getSeparator()).isEqualTo("\\");
    path.getFileSystem().getRootDirectories().forEach(System.out::println);
}


Using getName() and getNameCount()

The getNameCount() returns number of name components present in the path where each name component is seperated by a file seperator. And the method getName() takes an index and returns the name component at the index.

For example, a given path: /var/log/myapp/spring.log has four name components, and the component position is 0-based. So the name component at index 1 is log.

@Test
public void testGetName(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getName(0)).isEqualTo(Paths.get("src"));

    assertThat(path.getName(path.getNameCount() - 1))
            .isEqualTo(Paths.get("resources"));
}


Using getParent()

This API returns the path from the root of a path until it reaches the terminal directory or file (i.e excluding it). For example: invoking getParent() on a Path instance representing /var/log/myapp/spring.log returns a Path instance representing /var/log/myapp.

It returns null if the given path has no parent or if it is the root directory.

@Test
public void testGetParent(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getParent()).isEqualTo(Paths.get("src", "main"));
    assertThat(Paths.get("/").getParent()).isNull();
}


Using getRoot()

This API returns a Path instance of the root if it exists or null for a given instance of Path.

@Test
public void testGetRoot(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.getRoot()).isNull();

    path = Paths.get("/users", "Mohamed", "git", "blogsamples");
    assertThat(path.getRoot()).isEqualTo(Paths.get("/"));
}


Using normalize()

This API is a bit tricky. It removes redundant elements in your path. Redundant elements are those whose removal will eventually result in a similar Path. For example, the path src\..\src\main\java is equivalent to src\main\java. The normalize() API helps in achieving the latter from the former.

@Test
public void testNormalize(){
    Path path = Paths.get("src","..", "src", "main", "resources", ".");
    assertThat(path.toString())
            .isEqualTo("src\\..\\src\\main\\resources\\.");
    assertThat(path.normalize().toString())
            .isEqualTo("src\\main\\resources");
}


Using subpath()

This method returns a sub path identified by the lower bound and upper bound, which are passed as parameters to the method. The upper bound is excluded while computing the sub path.

@Test
public void testSubpath(){
    Path path = Paths.get("Mohamed", "git", 
            "blogsamples", "src", "main", "resources");
    assertThat(path.subpath(2, 3).toString()).isEqualTo("blogsamples");
    assertThat(path.subpath(0, path.getNameCount()).toString())
            .isEqualTo("Mohamed\\git\\blogsamples\\src\\main\\resources");
}


Using toAbsolutePath()

This method returns the absolute path for the given path. An absolute path originates from the root of the file system.

@Test
public void testToAbsolutePath(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.toAbsolutePath().toString())
       .isEqualTo("C:\\Users\\Mohamed\\git\\blogsamples\\src\\main\\resources");
}


Using toFile()

This is a very handy way to create an instance of java.io.File. We can leverage the use of creating a Path object with multiple folder levels, then use toFile() to get an instance of File.

@Test
public void testToFile(){
    Path path = Paths.get("src", "main", "resources");
    File file = path.toFile();
    assertThat(file).isNotNull();
    assertThat(file.isDirectory()).isTrue();
    assertThat(file.exists()).isTrue();
}


Using toRealPath()

This method can be used to resolve a symbolic link to its real location. To test this API, we create a symbolic link.

On Windows, you would use:

mklink /D "C:\blogsample" "C:\Users\Mohamed\git\blogsamples"


On Linux, you would use

ln -s /var/log/sample.log sample


The method takes an option of type LinkOption. As of now, this enum has one element: NOFOLLOW_LINKS. If this option is passed, then the symbolic link is not resolved to its real path.

@Test
public void testToRealPath() throws IOException {
    Path path = Paths.get( "/blogsample");
    assertThat(path.toRealPath().toString())
            .isEqualTo("C:\\Users\\Mohamed\\git\\blogsamples");
    assertThat(path.toRealPath(LinkOption.NOFOLLOW_LINKS).toString())
            .isEqualTo("C:\\blogsample");
}


Using toUri()

This method returns a URI representation of a given path. Generally, on Windows, you would see something in the form: file:///C:/. But this is system-dependent.

@Test
public void testToUri(){
    Path path = Paths.get("src", "main", "resources");
    assertThat(path.toUri()).isEqualTo(
      URI.create("file:///C:/Users/Mohamed/git/blogsamples/src/main/resources/"));
}


Note: It’s important to note that the return type of most of the API is an instance of java.nio.file.Path. This helps us in chaining multiple methods and invoking them on a single java.nio.file.Path instance.

In the next article, we will look at the remaining few APIs in java.nio.file.Path.

API

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • APIs for Logistics Orchestration: Designing for Compliance, Exceptions, and Edge Cases
  • Building Data Pipelines With Jira API

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!