Tag Archives: Java 7

Getting to know about java.nio.file.Path – 1


The last few released of Java namely Java 7, Java 8 and the upcoming Java 9 have quite a lot of features which makes the life 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 features or API was the enhancements 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.

    <!-- use 2.8.0 for Java 7 projects -->

Creating an instance of java.nio.file.Path

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

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

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

public void testPathCreation(){
    Path path = Paths.get("src", "main", "resources");

    Path uriPath = Paths.get(URI.create("file:///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.

public void testEndsWith(){
    Path path = Paths.get("src", "main", "resources");

Using getFileName()

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

public void testGetFileName(){
    Path path = Paths.get("src", "main", "resources");
    path = Paths.get("src", "test", "java", "info", 

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.

public void testGetFileSystem(){
    Path path = Paths.get("src", "main", "resources");

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 4 name components and the component position is 0 based. So the name component at index 1 is log.

public void testGetName(){
    Path path = Paths.get("src", "main", "resources");

    assertThat(path.getName(path.getNameCount() - 1))

Using getParent()

This API returns the path from the root of a path until 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.

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

Using getRoot()

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

public void testGetRoot(){
    Path path = Paths.get("src", "main", "resources");

    path = Paths.get("/users", "Mohamed", "git", "blogsamples");

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: if we have a path src\..\src\main\java is equivalent to src\main\java. The normalize() API helps in achieving the latter from the former.

public void testNormalize(){
    Path path = Paths.get("src","..", "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.

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())

Using toAbsolutePath()

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

public void testToAbsolutePath(){
    Path path = Paths.get("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 and then use toFile() to get an instance of File.

public void testToFile(){
    Path path = Paths.get("src", "main", "resources");
    File file = path.toFile();

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 i.e NOFOLLOW_LINKS. If this option is passed then the symbolic link is not resolved to its real path.

public void testToRealPath() throws IOException {
    Path path = Paths.get( "/blogsample");

Using toUri()

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

public void testToUri(){
    Path path = Paths.get("src", "main", "resources");

Note: It’s important to note that the return type of most of the APIs is an instance of java.nio.file.Path. This helps us in chaining multiple methods and invoke 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.


Various API and language enhancements as part of Java 7

I believe most of the Java Developers are aware of the latest Java release i.e Java 7. Lot of us are disappointed about quite a few important features being deferred to Java 8, but its really good to see the language evolving and lot of things happening in the Java community. You must have seen plethora of articles on try-with-resources, strings in switch statements and other minor language enhancements as part of Project Coin. These are just few of the enhancements added to the release. There are few other API enhancements which are good to know, for example new Files API in java.nio package, watching directory changes, Fork-Join framework.

I went through few of those topics and blogged about them and I thought it is best to aggregate them here for the benefit of the readers.

Fork-Join Framework:

In Java 5 java.util.concurrent package was added with lot of new classes for developing concurrent applications- Executor, ExecutorService, Callable, Futures among others. Fork-Join framework was added in Java 7 which builds on top of ExecutorService and adds task stealing algorithm in which the tasks queued in one thread can be picked by ideal threads and this facilitates creating multiple tasks and not worrying about tasks not getting executed.

  • A brief overview of Fork-Join framework can be found here.
  • Implementing mergesort algorithm using ForkJoin framework can be found here.

Enhancements to the File API:

A new package java.nio.file was added with support for representing file path, a static Files utility for reading, writing to a file and other file related tasks, working with symbolic links, api for implementing watch service and others.

There was another utility added to java.util package- Objects class with static utility methods for operating on object references. This is kind of unknown addition but has been used extensively in the Java 8 APIs. And I came across this while reading through the Java 8 code.

One other important feature added to the JVM- invokedynamic has been missed out here. And I think its quite important to explore this feature for there are languages like Groovy 2.0, JRuby making use of this feature.

Overview of the Java sessions at the Great Indian Dev Summit-2012

There was a lot to learn at the Java sessions of the GIDS 2012 with topics covering Java 7, Java 8, Concurrency in Java using STM model, Java EE 7 and its various JSRs, Scala, JavaScript among other topics. And not to forget a beautiful key note by Venkat Subramaniam about the need for developers to be familiar with multiple languages and how one can go forward in shaping their careers. The key-note, Java 7 session were very much similar to the one at GIDS 2011, but redundancy helps in learning better.

  • Each of the sessions were filled with technical content and lot of things to be learnt. I got an early peak into the Lambda expressions to be introduced in Java 8 and whole lot of other features to accompany that release. Also there was a quick walk through of Java 7 features.
  • The concurrency in Java session showed as to why the current concurrency model in Java is aptly called as synchronize and suffer model. We were shown how the Software Transactional Memory model of  Clojure could be made use of in Java as well.
  • We as Java developers dont spend much time writing  JavaScript and more so people working with component frameworks like JSF, ADF would spend even less time. During the session about JavaScript, there was a face-off between Java and JavaScript and how they are familiar and different.
  • There was a really good session on Scala by Venkat Subramaniam which stretched beyond the allotted 45 minutes into about 90 minutes. He covered concepts such as Tail Recursion, Traits, Val-Var, Classes and so on. I really appreciate the effort he put in and the dedication he showed in conveying and covering the concepts he intended to during the session which involved stretching out of the allotted time.
  • I by chance happened to sit in a session on creating RESTful WebService using JAX-RS and the new features in JAX-RS 2.0, though there was lot discussed, my eyes were paining seeing at the amount of code one had to write to create and consume the RESTful webservice. But for people of JavaEE stack that shouldn’t be much of concern.
  • Interesting to see lot of Goldman Sachs employees turning up at the GIDS 2012 and being present in their Expo booths. Also go to know about a Collection library developed by Goldman Sachs for their internal use which now they have open sourced. I have a copy of their source-code, binaries and some material which I would go through in the coming days and see if I can share some of my findings here. So looks like they are trying to build and sustain a good technical expertise inhouse.

So stuffs to try out:

  • Goldman Sachs Collections API
  • JavaScript and BackBone.js framework
  • Lambda expressions in Java 8
  • HTML 5 features

Java 7 Project Coin: try-with-resources explained with examples

Prior to “try-with-resources” (before Java 7) while dealing with SQL Statement or ResultSet or Connection objects or other IO objects one had to explicitly close the resource. So one would write something like-

//Create a resource- R
}catch(SomeException e){
//Hanlde the exception
//if resource R is not null then
//close the resource
catch(SomeOtherException ex){

Continue reading