<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Java 7.0</title>
	<atom:link href="http://www.javabeat.net/category/java-j2ee/java-7-0/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Wed, 22 May 2013 01:42:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Reading file asynchronously in Java</title>
		<link>http://www.javabeat.net/2012/08/reading-file-asynchronously-in-java/</link>
		<comments>http://www.javabeat.net/2012/08/reading-file-asynchronously-in-java/#comments</comments>
		<pubDate>Wed, 22 Aug 2012 18:20:21 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[nio]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4846</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>We all are familiar with reading/writing file in a synchronous way. In Java 7 a new API was added to read/write the contents of the file asynchronously. The API is AsynchronousFileChannel. In this example lets look at how to read the contents of the file asynchronously. There are two approaches to read the contents asynchronously: [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>We all are familiar with reading/writing file in a synchronous way. In Java 7 a new API was added to read/write the contents of the file asynchronously. The API is <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/AsynchronousFileChannel.html" target="_blank">AsynchronousFileChannel</a>.</p>
<p>In this example lets look at how to read the contents of the file asynchronously. There are two approaches to read the contents asynchronously:<br />
1. To use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html" target="_blank">Future</a> class to wait for the result of the read operation.<br />
2. To use a callback defined by the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/CompletionHandler.html" target="_blank">CompletionHandler</a> to process the result of the Asynchronous operation.</p>
<pre class="brush: java; title: ; notranslate">
//Using Future class to read the contents of the file.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.concurrent.*;

public class AsyncFutureRead {

  public static void main(String[] args) {

    //Buffer to read the contents from the file.
    ByteBuffer buffer = ByteBuffer.allocate(100);

    //The file to read the contents from.
    Path path = Paths.get(&quot;D:/tests/test.txt&quot;);

    //Creating the asynchronous channel to the file which allows reading and writing of content.
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path)){

      //Returns a Future instance which can be used to read the contents of the file.
      Future&lt;Integer&gt; fileResult = asyncChannel.read(buffer, 0);

      //Waiting for the file reading to complete.
      while(!fileResult.isDone()){
        System.out.println(&quot;Waiting to complete the file reading ...&quot;);
      }

      //Print the number of bytes read.
      System.out.println(&quot;Number of bytes read: &quot;+fileResult.get());

      //Reset the current position of the buffer to the beginning and the limit to the current position.
      buffer.flip();

      //Decode the contents of the byte buffer.
      System.out.println(&quot;Contents of file: &quot;);
      System.out.println(Charset.defaultCharset().decode(buffer));

    }catch(IOException | InterruptedException | ExecutionException ex){
      ex.printStackTrace();
    }
  }
}
</pre>
<h3>Buy Pro Java 7 NIO.2</h3>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank"><img class="alignleft alignnone" src="http://img6.flixcart.com/image/book/1/7/0/pro-java-7-nio-2-275x275-imad7wkerzzjzvnd.jpeg" alt="" width="95" height="125" /></a></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank">Pro Java 7 NIO.2</a> by Anghel Leonard (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1430240113" target="_blank">Amazon.com</a> / <a href="http://astore.amazon.com/javabeat-20/detail/B006JPPN0W" target="_blank">Kindle Edition</a> )</p>
<p>Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjava-j2ee%2Fjava-7-0%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/java-j2ee/java-7-0/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/java-j2ee/java-7-0/feed/" data-count="vertical" data-text="Java 7.0" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/08/reading-file-asynchronously-in-java/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visiting all the files and directories for a directory in Java using NIO2</title>
		<link>http://www.javabeat.net/2012/07/visiting-all-the-files-and-directories-for-a-directory-in-java-using-nio2/</link>
		<comments>http://www.javabeat.net/2012/07/visiting-all-the-files-and-directories-for-a-directory-in-java-using-nio2/#comments</comments>
		<pubDate>Sun, 22 Jul 2012 17:35:06 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[nio2]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4769</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>At times we might want to search for some file in a directory traversing recursively into other directories with in that directory, I know getting the recursive program right at the first time is always a challenge. Or we might want to list all the contents of a directory. For all these operations the NIO2 [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>At times we might want to search for some file in a directory traversing recursively into other directories with in that directory, I know getting the recursive program right at the first time is always a challenge. Or we might want to list all the contents of a directory. For all these operations the <a href="http://www.javabeat.net/tag/nio2/" target="_blank">NIO2</a> enhancements in <a href="http://www.javabeat.net/category/java-j2ee/java-7-0/" target="_blank">Java 7</a> provides an API to recursively traverse through a path and another interface which can be extended to provide hooks for performing certain operations when a file is encountered or a directory is encountered. </p>
<p>The method used is: <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#walkFileTree%28java.nio.file.Path,%20java.util.Set,%20int,%20java.nio.file.FileVisitor%29" target="_blank">Files.walkFileTree</a>. There are 2 overloaded versions of this method: </p>
<pre class="brush: java; title: ; notranslate">
public static Path walkFileTree(Path start,
              Set&lt;FileVisitOption&gt; options,
              int maxDepth,
              FileVisitor&lt;? super Path&gt; visitor)
                       throws IOException
</pre>
<p>and </p>
<pre class="brush: java; title: ; notranslate">
public static Path walkFileTree(Path start,
    FileVisitor&lt;? super Path&gt; visitor)
             throws IOException
</pre>
<p>Currently <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileVisitOption.html" target="_blank">FileVisitOption</a> enum provides an option to specify whether or not to follow the symbolic links. The <strong>maxDepth</strong> restricts the number of levels the walkFileTree method would traverse into for a given directory. </p>
<p>The <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileVisitor.html" target="_blank">FileVisitor</a> interface is the major player in this operation. It has the following methods:</p>
<ul>
<li><strong>postVisitDirectory(T dir, IOException exc)</strong>: Invoked for a directory after entries in the directory, and all of their descendants, have been visited.</li>
<li><strong>preVisitDirectory(T dir, BasicFileAttributes attrs)</strong>: Invoked for a directory before entries in the directory are visited.</li>
<li><strong>visitFile(T file, BasicFileAttributes attrs)</strong>: Invoked for a file in a directory.</li>
<li><strong>visitFileFailed(T file, IOException exc)</strong>: Invoked for a file that could not be visited.</li>
</ul>
<p>Each of these methods return a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileVisitResult.html" target="_blank">FileVisitResult</a>, which is another enum with the following constants:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li><strong>CONTINUE</strong>: Continue.</li>
<li><strong>SKIP_SIBLINGS</strong>: Continue without visiting the siblings of this file or directory.</li>
<li><strong>SKIP_SUBTREE</strong>: Continue without visiting the entries in this directory.</li>
<li><strong>TERMINATE</strong>: Terminate.</li>
</ul>
<p>I have created a test dir with the following contents:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/07/Dir11.png"><img src="http://www.javabeat.net/wp-content/uploads/2012/07/Dir11.png" alt="" width="128" height="146" class="aligncenter size-full wp-image-4774" /></a><br />
and the dir1 contains:<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/07/Dir21.png"><img src="http://www.javabeat.net/wp-content/uploads/2012/07/Dir21.png" alt="" width="128" height="127" class="aligncenter size-full wp-image-4775" /></a></p>
<p>Lets write a program to list all the text files in the folder: &#8220;D:\nioTestDir&#8221;. First we need to implement the FileVisitor interface. We can make use of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/SimpleFileVisitor.html">SimpleFileVisitor</a> class which implements the FileVisitor interface and provides default operations for all the methods.</p>
<pre class="brush: java; title: ; notranslate">
class TextFileVisitor extends SimpleFileVisitor&lt;Path&gt;{
  
  PathMatcher matcher;
  
  public TextFileVisitor(){
    
    matcher = FileSystems.getDefault().getPathMatcher(&quot;glob:*.txt&quot;);
    
  }
  
  @Override
  public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
      throws IOException {
    
    Path fileName = file.getFileName();
    
    if ( matcher.matches(fileName)){
      System.out.println(&quot;Found: &quot;+ file);
    }
    
    //Continue to search for other txt files
    return FileVisitResult.CONTINUE;
  }
  
}
</pre>
<p>and the complete program to find the &#8220;*.txt&#8221; files is:</p>
<pre class="brush: java; title: ; notranslate">
public class DirectoryScanner {
  
  public static void main(String[] args) throws IOException {
    
    Path rootPath = Paths.get(&quot;D:/nioTestDir&quot;);
    Files.walkFileTree(rootPath, new TextFileVisitor());
    
  }

}
</pre>
<p>the output: </p>
<pre class="brush: bash; title: ; notranslate">
Found: D:\nioTestDir\dir1\dir1Test1.txt
Found: D:\nioTestDir\dir1\dir1Test2.txt
Found: D:\nioTestDir\dir1\dir1Test3.txt
Found: D:\nioTestDir\test1.txt
Found: D:\nioTestDir\test2.txt
Found: D:\nioTestDir\test3.txt
</pre>
<p>This new API has made it really easy to traverse any given path to get the contents of the file/directory represented by the path. The above example was a simple way to list all the &#8220;.txt&#8221; files in the given path. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/visiting-all-the-files-and-directories-for-a-directory-in-java-using-nio2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Listing and filtering directory content using Java NIO2</title>
		<link>http://www.javabeat.net/2012/07/listing-and-filtering-directory-content-using-java-nio2/</link>
		<comments>http://www.javabeat.net/2012/07/listing-and-filtering-directory-content-using-java-nio2/#comments</comments>
		<pubDate>Thu, 19 Jul 2012 18:36:25 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[nio2]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4766</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>The Files class provides a method- newDirectoryStream to get the Directory contents for a give path instance. There are other overloaded versions of newDirectoryStream method which take in filters to apply on the directory content. Listing all files in the directory Using Files.newDirectoryStream method gives an instance of DirectoryStream class which is a Iterable i.e [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>The <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" title="Files" target="_blank">Files</a> class provides a method- <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream%28java.nio.file.Path%29" title="newDirectoryStream" target="_blank">newDirectoryStream</a> to get the Directory contents for a give path instance. There are other overloaded versions of newDirectoryStream method which take in filters to apply on the directory content. </p>
<h3>Listing all files in the directory</h3>
<p>Using <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream%28java.nio.file.Path%29" target="_blank">Files.newDirectoryStream</a> method gives an instance of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html" target="_blank">DirectoryStream</a> class which is a Iterable i.e one can get iterate over its contents. Also it implements AutoCloseable, Closeable which means that one can make use of try with resources to close the directory stream after use. </p>
<pre class="brush: java; title: ; notranslate">
Path basePath = Paths.get(&quot;D:/tests&quot;);

// Listing the files in the directory
System.out.println(&quot;All files:&quot;);
try (DirectoryStream&lt;Path&gt; pathList = Files.newDirectoryStream(basePath)) {
  for (Path path : pathList) {
    System.out.println(path.toString());
  }

} catch (IOException e) {

  e.printStackTrace();
}
</pre>
<p><strong>Output</strong>:</p>
<pre class="brush: bash; title: ; notranslate">
All files:
D:\tests\another_test.txt
D:\tests\DirectoryFilterTest.class
D:\tests\somDoc.docx
D:\tests\test1.txt
</pre>
<h3>Applying Filter using GLOB pattern</h3>
<p>In the above sample we listed all the files, we can even use regular expression strings to restrict the files to be obtained from the directory. This regular expression structure is called as a GLOB pattern. Some rules for Glob pattern are:</p>
<ul>
<li>* represents any number of characters</li>
<li>? represents a single character</li>
<li>{} represents a collection of patterns like {txt,doc}</li>
<li>[] represents a set of single characters like [A-Z], [0-9]</li>
</ul>
<p>Using the Glob pattern we would restrict to fetch only the txt files</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
try (DirectoryStream&lt;Path&gt; pathList = 
  Files.newDirectoryStream(basePath,&quot;*.txt&quot;)) {
  for (Path path : pathList) {
    System.out.println(path.toString());
  }

} catch (IOException e) {

  e.printStackTrace();
}
</pre>
<p><strong>Output</strong>:</p>
<pre class="brush: bash; title: ; notranslate">
All text files[Using Glob pattern]:
D:\tests\another_test.txt
D:\tests\test1.txt
</pre>
<h3>Applying filter using the DirectoryStream.Filter class</h3>
<p>Another approach to apply filter is to extend the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.Filter.html" target="_blank">DirectoryStream.Filter</a> class and overrides its accept(Path) method. The paths for which the accept(Path) method returns true would be fetched and listed.<br />
The same example above implemented using DirectoryStream.Filter:</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;All document files[Using Filter class]&quot;);
DirectoryStream.Filter&lt;Path&gt; documentFilter = new DirectoryStream.Filter&lt;Path&gt;() {

  @Override
  public boolean accept(Path entry) throws IOException {
    String fileName = entry.getFileName().toString();
    return fileName != null &amp;&amp; fileName.endsWith(&quot;txt&quot;);
  }

};
try (DirectoryStream&lt;Path&gt; pathList = Files.newDirectoryStream(basePath,
    documentFilter)) {
  for (Path path : pathList) {
    System.out.println(path.toString());
  }

} catch (IOException e) {

  e.printStackTrace();
}
</pre>
<p><strong>Output:</strong></p>
<pre class="brush: bash; title: ; notranslate">
All document files[Using Filter class]
D:\tests\another_test.txt
D:\tests\test1.txt
</pre>
<p>Its clear that for filtering based on file names glob patterns is the preferred approach and for filtering based on other parameters like file size, file attributes using DirectoryStream.Filter is the better approach. </p>
<p>The complete code for this can be found <a href="https://gist.github.com/3145846" target="_blank">here</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/listing-and-filtering-directory-content-using-java-nio2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating Hard links and Soft links for a file in Java</title>
		<link>http://www.javabeat.net/2012/07/creating-hard-links-and-soft-links-for-a-file-in-java/</link>
		<comments>http://www.javabeat.net/2012/07/creating-hard-links-and-soft-links-for-a-file-in-java/#comments</comments>
		<pubDate>Tue, 17 Jul 2012 15:46:13 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4752</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>We have been exploring the NIO enhancements in Java 7 and in this post I will explain about creating links- Hard links and Soft links in Java. And this feature is part of Java 7. A link is kind of substitute name to access a particular file/directory, something like an alias to the file/directory. This [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>We have been exploring the NIO enhancements in <a href="http://www.javabeat.net/category/java-7-0/" target="_blank">Java 7</a> and in this post I will explain about creating links- Hard links and Soft links in Java. And this feature is part of Java 7.</p>
<p>A link is kind of substitute name to access a particular file/directory, something like an alias to the file/directory. This way it allows us to refer to a file/directory by more than one name. There are 2 types of links that can be created:</p>
<ul>
<li><strong>Symbolic Links:</strong> These links refer to the file/directory path. And using these links can be used to directly operate on the path they refer to. In my daily work I use a lot of symbolic links and they are really flexible. In this case if the file to which the link refers to is deleted, the link continues to exist but it is not a valid link.</li>
<li><strong>Hard Links:</strong> These links are more stricter than symbolic links which refer to the physical location of the file. If the content of the original file is changed, the link also gets updated whereas if the original file is deleted, the link continues to exist and is valid file.</li>
</ul>
<h3>Creating Symbolic Links in Java</h3>
<p>Not all operating systems support creating symbolic links. The program I tried on Windows couldn&#8217;t create a symbolic link. But for creating symbolic link we make use of the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createSymbolicLink(java.nio.file.Path, java.nio.file.Path, java.nio.file.attribute.FileAttribute...)" target="_blank">Files.createSymbolicLink</a> method which takes the link path as well as the target path, where both link and target are instances of type <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html" target="_blank">Path</a>.</p>
<h3>Creating Hard links in Java</h3>
<p>On Windows I was able to create the Hard links and for this we make use of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createLink(java.nio.file.Path, java.nio.file.Path)" target="_blank">Files.createLink</a> method which takes in link path and the target path.<br />
Lets look at the example where both soft link and hard links are created:<br />
Note: I tried this sample on Windows and Linux, but you can get better results in Linux, because I am not sure how to list the links in Windows.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
public class LinkTest {
  public static void main(String[] args) throws IOException {
    Path file1 = Paths.get(&quot;test1&quot;);
    System.out.println(file1.toRealPath());
    Path hLink = Paths.get(&quot;test1.hLink&quot;);
    Path sLink = Paths.get(&quot;test1.symLink&quot;);

    try{
      Files.createSymbolicLink(sLink, file1);

    }catch(UnsupportedOperationException ex){
      System.out.println(&quot;This OS doesn't support creating Sym links&quot;);
    }

    try{
      Files.createLink(hLink, file1);
      System.out.println(hLink.toRealPath());
    }catch(UnsupportedOperationException ex){
      System.out.println(&quot;This OS doesn't support creating Sym links&quot;);
    }

  }
}
</pre>
<h3>Buy Pro Java 7 NIO.2</h3>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank"><img class="alignleft alignnone" src="http://img6.flixcart.com/image/book/1/7/0/pro-java-7-nio-2-275x275-imad7wkerzzjzvnd.jpeg" alt="" width="95" height="125" /></a></p>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank">Pro Java 7 NIO.2</a> by Anghel Leonard (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1430240113" target="_blank">Amazon.com</a> / <a href="http://astore.amazon.com/javabeat-20/detail/B006JPPN0W" target="_blank">Kindle Edition</a> )</p>
<p>Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/creating-hard-links-and-soft-links-for-a-file-in-java/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Obtaining and modifying the metadata of the files in Java 7 NIO.2</title>
		<link>http://www.javabeat.net/2012/07/obtaining-and-modifying-the-metadata-of-the-files-in-java-7-nio-2/</link>
		<comments>http://www.javabeat.net/2012/07/obtaining-and-modifying-the-metadata-of-the-files-in-java-7-nio-2/#comments</comments>
		<pubDate>Fri, 13 Jul 2012 04:30:29 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4737</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Files usually contain information like its creation time, last modified time, last accessed time, size, type, permissions, ownership and other details which constitute its metadata. NIO.2 enhancements in Java 7 adds views to obtain metadata information of the file. The file attributes are grouped into different views based on their relatedness and applicability, for example [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Files usually contain information like its creation time, last modified time, last accessed time, size, type, permissions, ownership and other details which constitute its metadata. NIO.2 enhancements in Java 7 adds views to obtain metadata information of the file. The file attributes are grouped into different views based on their relatedness and applicability, for example general file attributes like size, last modified time, last accessed time, creation time are grouped as one and other Unix based permissions information in grouped into one view and so on.</p>
<p>Various views supported in NIO.2 are:</p>
<ul>
<li><strong><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/BasicFileAttributeView.html" target="_blank">BasicFileAttributeView</a></strong>: A file attribute view that provides a view of a basic set of file attributes common to many file systems. The basic set of file attributes consist of mandatory and optional file attributes as defined by the BasicFileAttributes interface. This view is named as &#8220;basic&#8221;</li>
<li><strong><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/DosFileAttributeView.html" target="_blank">DosFileAttributeView</a></strong>: Extends the BasicFileAttributeView and adds the four supported attributes on file systems that support the DOS attributes. This view is named as &#8220;dos&#8221;.</li>
<li><strong><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/PosixFileAttributeView.html" target="_blank">PosixFileAttributeView</a></strong>: This extends the BasicFileAttributeView with attributes supported on file systems that supports POSIX standards such as Unix. This view is named as: &#8220;posix&#8221;</li>
<li><strong><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/UserDefinedFileAttributeView.html" target="_blank">UserDefinedFileAttributeView</a></strong>: One can specify custom attributes using this view.</li>
<li><strong><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/AclFileAttributeView.html" target="_blank">AclFileAttributeView</a></strong>: This view supports obtaining file&#8217;s access control list. It is named as &#8220;acl&#8221;.</li>
<li><strong><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/FileOwnerAttributeView.html" target="_blank">FileOwnerAttributeView</a></strong>: Any file system that supports file owners would provide this view. This is used to obtain the owner information for the file. This view is named as &#8220;owner&#8221;.</li>
</ul>
<p>For each of the views I have also mentioned the view names and its important to know these view names because one can refer to the attributes using [view-name]:attributeName. Before you access the views you need to make sure that the file/file system/file store supports the view. For example On Windows OS you cannot find PosixFileAttributeView and on Unix no DosFileAttributeView. Lets see how one can find out the view supported. One can find out the views supported per file or even at the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileStore.html" target="_blank">FileStore</a> level.</p>
<pre class="brush: java; title: ; notranslate">
FileSystem fileSystem = FileSystems.getDefault();

for(FileStore store : fileSystem.getFileStores()){
  System.out.println(store.toString());
  for (String view : fileSystem.supportedFileAttributeViews()){
    if ( store.supportsFileAttributeView(view)){
      System.out.print(view+&quot;,&quot;);
    }
  }
  System.out.println(&quot;&quot;);
}
</pre>
<p>On my machine the output for the above code is:</p>
<pre class="brush: java; title: ; notranslate">
Windows (C:)
acl,basic,owner,user,dos
ImptStuff (D:)
acl,basic,owner,user,dos
Entertainment (E:)
acl,basic,owner,user,dos
</pre>
<p>FileStore gives a list of all partitions on my file system and then for each partition find out the views supported.</p>
<p>Going ahead we would pick one file and then find out the attributes associated with the file.</p>
<h4>Basic Attributes view</h4>
<p>A basic attributes view would provide: creation time, last modified time, last accessed time, size, file type, file key. All the views have an associated attributes class like BasicFileAttributeView has <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/BasicFileAttributes.html" target="_blank">BasicFileAttrbutes</a> class which can be used to obtain the values of these attributes.</p>
<pre class="brush: java; title: ; notranslate">
/* Attributes of Basic View */
Path path1 = Paths.get(&quot;test1&quot;);

BasicFileAttributes basicAttributes =
  Files.readAttributes(path1, BasicFileAttributes.class);

System.out.println(&quot;Creation Time: &quot;+basicAttributes.creationTime());
System.out.println(&quot;Directory? &quot;+basicAttributes.isDirectory());
System.out.println(&quot;File? &quot;+basicAttributes.isRegularFile());
System.out.println(&quot;Last accessed on: &quot;+basicAttributes.lastAccessTime());
System.out.println(&quot;Last modified on: &quot;+basicAttributes.lastModifiedTime());
System.out.println(&quot;File size: &quot;+basicAttributes.size()+&quot;bytes&quot;);

</pre>
<p>The output for the above code:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
Creation Time: 2012-06-20T17:32:09.703125Z
Directory? false
File? true
Last accessed on: 2012-07-12T17:00:28.234Z
Last modified on: 2012-07-12T17:00:28.234Z
File size: 61bytes
</pre>
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" target="_blank">Files</a> is the class which is used for all the operations related to file attributes- getting and setting their values. One can even use getAttribute method of Files class to get the required attribute:</p>
<pre class="brush: java; title: ; notranslate">
FileTime lastModifiedTime =
  (FileTime)Files.getAttribute(path1, &quot;basic:lastModifiedTime&quot;);
</pre>
<p>One can even modfiy the attribute values. I am not sure if other values can be modified but I was able to modify the time related information. Again you make use of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" target="_blank">Files</a> class to modify the attribute values.</p>
<pre class="brush: java; title: ; notranslate">
/* Modifying file attribute */

FileTime newTime = FileTime.fromMillis(System.currentTimeMillis());
Files.setLastModifiedTime(path1, newTime);

BasicFileAttributeView bAttributesView =
    Files.getFileAttributeView(path1, BasicFileAttributeView.class);
bAttributesView.setTimes(null, newTime, null);
</pre>
<p>One can make use of Files.setAttribute() to modify the attribute. In the above example we used setLastModifiedTime for modifying the lastModifiedTime attribute, then we made use of BasicFileAttributeView to modify the creation, last modified, and last access attributes by using the setTimes method which takes in 3 parameters representing the last modified, last access time, and creation time as instances of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/FileTime.html" target="_blank">FileTime</a> class.</p>
<p>This was a quick overview of the Basic file attributes. One can explore the other views to find out the attributes supported by that view.</p>
<h3>Buy Pro Java 7 NIO.2</h3>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank"><img class="alignleft alignnone" src="http://img6.flixcart.com/image/book/1/7/0/pro-java-7-nio-2-275x275-imad7wkerzzjzvnd.jpeg" alt="" width="95" height="125" /></a></p>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank">Pro Java 7 NIO.2</a> by Anghel Leonard (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1430240113" target="_blank">Amazon.com</a> / <a href="http://astore.amazon.com/javabeat-20/detail/B006JPPN0W" target="_blank">Kindle Edition</a> )</p>
<p>Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/obtaining-and-modifying-the-metadata-of-the-files-in-java-7-nio-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Exploring the Path API &#8211; Java NIO enhancement in Java 7</title>
		<link>http://www.javabeat.net/2012/07/exploring-the-path-api-java-nio-enhancement-in-java-7/</link>
		<comments>http://www.javabeat.net/2012/07/exploring-the-path-api-java-nio-enhancement-in-java-7/#comments</comments>
		<pubDate>Thu, 12 Jul 2012 06:30:08 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4729</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>All of us know that an instance of File doesn&#8217;t indicate a file in the file system, unless some one invokes a create or related methods. But its a kind of confusion- you talk about instance of File and then you also talk about file at the disk level. A new class was introduced in [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>All of us know that an instance of <a href="http://docs.oracle.com/javase/7/docs/api/java/io/File.html" target="_blank">File</a> doesn&#8217;t indicate a file in the file system, unless some one invokes a create or related methods. But its a kind of confusion- you talk about instance of File and then you also talk about file at the disk level. A new class was introduced in Java 7 as part of the NIO enhancements which allows to represent the files at the disk level in the memory/as part of objects in Java and this new class is the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html" target="_blank">Path</a> class. And I have used this class extensively in my posts about Files API <a title="A peek into the Files utility which is part of java.nio package in Java 7" href="http://www.javabeat.net/2012/06/a-peek-files-utility-part-java-nio-package-java-7/">here</a> and <a title="Creating, Writing, Reading files using Java Files API of Java 7" href="http://www.javabeat.net/2012/06/creating-writing-reading-java-files-api-java-7/">here</a> and also about <a title="Implementing WatchService API in Java 7 to monitor the directory changes" href="http://www.javabeat.net/2012/06/watchservice-api-java7-monitor-directory/">WatchService API</a>.</p>
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html" target="_blank">Path</a> is an interface and there is a factory <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Paths.html" target="_blank">Paths</a> which can be used to create instances of type Path. Lets look at some of the operations/functionality provided by Paths and Path classes.</p>
<h4>Defining Path</h4>
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Paths.html" target="_blank">Paths</a> class provides a get(URI), get(String, String &#8230;) methods to obtain a Path instance for given file/directory.</p>
<h6>Using Absolute Path</h6>
<pre class="brush: java; title: ; notranslate">
Path path1 = Paths.get(&quot;E:/Back Up/OSLabs/priority.c&quot;);

Path invalidPath = Paths.get(&quot;E:/Back Up/OSLabs/invalid&quot;);

try{
  System.out.println(invalidPath.toRealPath());
}
catch(NoSuchFileException ex){
  System.out.println(invalidPath.toString()+&quot; not found&quot;);
}
//output: E:\Back Up\OSLabs\invalid not found
</pre>
<p>In the above example we have a valid path and another invalid path. These Path instances dont really check if the location uses if valid or not, but one can use toRealPath() which checks if the given path is valid or not.</p>
<h6>Using Relative Path</h6>
<pre class="brush: java; title: ; notranslate">
Path relPath1 = Paths.get(&quot;test1&quot;);
Path relPath2 = Paths.get(&quot;test2&quot;);
System.out.println(relPath1.toRealPath());
//output: C:\Documents and Settings\Mohamed Sanaulla\My Documents\NetBeansProjects\JavaBeatSamples\test1
</pre>
<h6>Using FileSystem to construct Path</h6>
<p>Java 7 NIO enhancements added a new <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html" target="_blank">FileSystem</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html" target="_blank">FileSystems</a> class to get the instance of underlying file system. An instance of Path can also be created using getPath() method of the FileSystem class.</p>
<pre class="brush: java; title: ; notranslate">
FileSystem fs = FileSystems.getDefault();
Path fsPath1 = fs.getPath(&quot;/dev/Test.java&quot;);
Path fsPath2 = fs.getPath(&quot;test1&quot;);
System.out.println(fsPath1.toRealPath());
System.out.println(fsPath2.toRealPath());
//output:
//C:\dev\Test.java
//C:\Documents and Settings\Mohamed Sanaulla\My Documents\NetBeansProjects\JavaBeatSamples\test1
</pre>
<h4>What all information can be obtained from Path?</h4>
<p>Path class provides methods to get the name of the file, the parent path of the file, the root of the file and also an Iterator to get different elements of the Path string. Lets look at an example below:</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;Information from the Path&quot;);
System.out.println(&quot;Path Name: &quot;+path1.getFileName());
System.out.println(&quot;Path Parent: &quot;+path1.getParent());
System.out.println(&quot;Path Root: &quot;+path1.getRoot());
System.out.println(&quot;Number of elements in path: &quot;+path1.getNameCount());
for ( int i = 0; i &lt; path1.getNameCount(); i++){
  System.out.println(&quot;Element &quot;+i+&quot;: &quot;+path1.getName(i));
}
System.out.println(&quot;Subpath: &quot;+path1.subpath(0,2));
/*
output:
Information from the Path
Path Name: priority.c
Path Parent: E:\Back Up\OSLabs
Path Root: E:\
Number of elements in path: 3
Element 0: Back Up
Element 1: OSLabs
Element 2: priority.c
Subpath: Back Up\OSLabs*/
</pre>
<h4>Comparing Paths</h4>
<p>One can compare the paths using equals() which checks for content equality, compareTo() which can be overridden for correct comparison and the Files.isSameFile method which can be used to check if the two path instances actually refer to the same file on the disk. An example for the same:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;Path comparisions&quot;);
Path compPath1 = Paths.get(&quot;/dev/Test.java&quot;);
Path compPath2 = Paths.get(&quot;C:/dev/Test.java&quot;);
System.out.println(&quot;Using Equals: &quot;+compPath1.equals(compPath2));
System.out.println(&quot;Using isSameFile: &quot;+Files.isSameFile(compPath1, compPath2));
/*
Output:
Path comparisions
Using Equals: false
Using isSameFile: true
*/
</pre>
<p>In the above example though compPath1 and compPath2 represented same file their string content was different. Hence equals() told that they are different where as isSameFile told that they are same.</p>
<h4>Converting Path to File and URI</h4>
<p>One can convert the Path instance into URI format and also create a File instance out of it.</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;Path conversions&quot;);
System.out.println(&quot;String: &quot;+fsPath1.toString());
System.out.println(&quot;URI: &quot;+fsPath1.toUri());
File fileFsPath1 = fsPath1.toFile();
System.out.println(&quot;File: &quot;+fileFsPath1.exists());
/*
Output:
Path conversions
String: \dev\Test.java
URI: file:///C:/dev/Test.java
File: true
*/
</pre>
<h4>Combining different paths</h4>
<p>We can create one base path and then build multiple paths from that base path using the resolve() method, something like:</p>
<pre class="brush: java; title: ; notranslate">
System.out.println(&quot;Combining Paths&quot;);
Path basePath = Paths.get(&quot;C:/dev&quot;);
Path newPath1 = basePath.resolve(&quot;Test.java&quot;);
System.out.println(&quot;Same file? &quot;+Files.isSameFile(compPath2, newPath1));
Path newPath2 = basePath.resolve(&quot;java/CloneTest.java&quot;);
System.out.println(newPath2.toRealPath());
/*
Output:
Combining Paths
Same file? true
C:\dev\java\CloneTest.java
*/
</pre>
<p>These were some of the APIs associated with Path class.</p>
<h3>Buy Pro Java 7 NIO.2</h3>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank"><img class="alignleft alignnone" src="http://img6.flixcart.com/image/book/1/7/0/pro-java-7-nio-2-275x275-imad7wkerzzjzvnd.jpeg" alt="" width="95" height="125" /></a></p>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank">Pro Java 7 NIO.2</a> by Anghel Leonard (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1430240113" target="_blank">Amazon.com</a> / <a href="http://astore.amazon.com/javabeat-20/detail/B006JPPN0W" target="_blank">Kindle Edition</a> )</p>
<p>Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/exploring-the-path-api-java-nio-enhancement-in-java-7/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Creating, Writing, Reading files using Java Files API of Java 7</title>
		<link>http://www.javabeat.net/2012/06/creating-writing-reading-java-files-api-java-7/</link>
		<comments>http://www.javabeat.net/2012/06/creating-writing-reading-java-files-api-java-7/#comments</comments>
		<pubDate>Wed, 20 Jun 2012 18:30:44 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4400</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In our previous post we did get a taste of the power of the static APIs in the Java Files class and we managed to compare the code written without using the APIs in Java Files and with using the APIs in Java Files. In this post let me delve further into the other APIs [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In our <a title="A peek into the Java Files utility which is part of java.nio package in Java 7" href="http://www.javabeat.net/2012/06/a-peek-files-utility-part-java-nio-package-java-7/">previous post</a> we did get a taste of the power of the static APIs in the Java <a title="Files API" href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" target="_blank">Files</a> class and we managed to compare the code written without using the APIs in Java Files and with using the APIs in Java Files.</p>
<p>In this post let me delve further into the other APIs offered by Java <a title="Files API" href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" target="_blank">Files</a> class and look at the creation, deletion of files and reading and writing to the files.</p>
<h3>Creating and Deleting a file:</h3>
<pre class="brush: java; title: ; notranslate">
//Create a new Path
Path newFile = Paths.get(&quot;test1&quot;);
try {
  Files.deleteIfExists(newFile);
  newFile = Files.createFile(newFile);
} catch (IOException ex) {
  System.out.println(&quot;Error creating file&quot;);
}
System.out.println(Files.exists(newFile));
</pre>
<p>Creating a new <a title="Path" href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html" target="_blank">Path</a>object doesn&#8217;t create a file on the file system. A Path object just indicates a file/directory or any other resource location. The resource might or might not be present in the identified location.</p>
<h3>Writing to the file using BufferedWriter:</h3>
<p>In the above code we create a file, which contains no data. Lets now write something to the file:</p>
<pre class="brush: java; title: ; notranslate">
//Writing to file
try(BufferedWriter writer = Files.newBufferedWriter(
        newFile, Charset.defaultCharset())){
  writer.append(&quot;This is first line&quot;);
  writer.newLine();
  writer.append(&quot;This is second line&quot;);
  writer.newLine();
  writer.append(&quot;This is third line&quot;);
  writer.newLine();
  writer.flush();
}catch(IOException exception){
  System.out.println(&quot;Error writing to file&quot;);
}
</pre>
<p>The interesting piece from the above code is:</p>
<pre class="brush: java; title: ; notranslate">
try(BufferedWriter writer = Files.newBufferedWriter(
        newFile, Charset.defaultCharset())){
</pre>
<p>where we make use of the static API <strong>newBuffredWriter</strong> in Java <a title="Files API" href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" target="_blank">Files</a> to obtain the BufferedWriter for the file. And also we make use of the try-with-resources construct to get rid of the finally clause.</p>
<h3>Reading from the file using BufferedReader:</h3>
<p>Now that we have some content in the file, lets read the content back and display it on the console.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
//Reading from file
try(BufferedReader reader = Files.newBufferedReader(
        newFile, Charset.defaultCharset())){
  String lineFromFile = &quot;&quot;;
  System.out.println(&quot;The contents of file are: &quot;);
  while((lineFromFile = reader.readLine()) != null){
    System.out.println(lineFromFile);
  }

}catch(IOException exception){
  System.out.println(&quot;Error while reading file&quot;);
}
</pre>
<p>We ended up making use of the static API <strong>newBufferedReader</strong> to read the contents of the file and print it on the console.</p>
<p>The advantage of using the Java Files API is that the code is more readable than before and also the parts of the code encapsulated by the API can be reusable.</p>
<p>Here is the complete code for the above example:</p>
<pre class="brush: java; title: ; notranslate">
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class NewFilesApiTest {
  public static void main(String[] args)  {

    //Creating a new file
    Path newFile = Paths.get(&quot;test1&quot;);
    try {
      Files.deleteIfExists(newFile);
      newFile = Files.createFile(newFile);
    } catch (IOException ex) {
      System.out.println(&quot;Error creating file&quot;);
    }
    System.out.println(Files.exists(newFile));

    //Writing to file
    try(BufferedWriter writer = Files.newBufferedWriter(
            newFile, Charset.defaultCharset())){
      writer.append(&quot;This is first line&quot;);
      writer.newLine();
      writer.append(&quot;This is second line&quot;);
      writer.newLine();
      writer.append(&quot;This is third line&quot;);
      writer.newLine();
      writer.flush();
    }catch(IOException exception){
      System.out.println(&quot;Error writing to file&quot;);
    }

    //Reading from file
    try(BufferedReader reader = Files.newBufferedReader(
            newFile, Charset.defaultCharset())){
      String lineFromFile = &quot;&quot;;
      System.out.println(&quot;The contents of file are: &quot;);
      while((lineFromFile = reader.readLine()) != null){
        System.out.println(lineFromFile);
      }

    }catch(IOException exception){
      System.out.println(&quot;Error while reading file&quot;);
    }
  }

}
</pre>
<p>The output is:</p>
<pre class="brush: bash; title: ; notranslate">
true
The contents of file are:
This is first line
This is second line
This is third line
</pre>
<h3>Buy Pro Java 7 NIO.2</h3>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank"><img class="alignleft alignnone" src="http://img6.flixcart.com/image/book/1/7/0/pro-java-7-nio-2-275x275-imad7wkerzzjzvnd.jpeg" alt="" width="95" height="125" /></a></p>
<p><a href="http://www.flipkart.com/pro-java-7-nio-2-8132206177/p/itmd73ah7ffvdeqg?pid=9788132206170&amp;affid=suthukrish" target="_blank">Pro Java 7 NIO.2</a> by Anghel Leonard (buy from <a href="http://astore.amazon.com/javabeat-20/detail/1430240113" target="_blank">Amazon.com</a> / <a href="http://astore.amazon.com/javabeat-20/detail/B006JPPN0W" target="_blank">Kindle Edition</a> )</p>
<p>Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/creating-writing-reading-java-files-api-java-7/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A peek into the Files utility which is part of java.nio package in Java 7</title>
		<link>http://www.javabeat.net/2012/06/a-peek-files-utility-part-java-nio-package-java-7/</link>
		<comments>http://www.javabeat.net/2012/06/a-peek-files-utility-part-java-nio-package-java-7/#comments</comments>
		<pubDate>Mon, 18 Jun 2012 06:00:59 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[Files]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4318</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>We recently wrote about watching a directory using the new APIs introduced as part of Java 7. In this post let me throw some light on another class added to the java.nio package as part of Java 7 update- java.nio.file.Files. Another piece of information related to this is that complete java.nio.file package was added as [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>We recently wrote about <a title="Watching a directory for changes using File NIO in Java 7" href="http://www.javabeat.net/2012/06/watching-a-directory-for-changes-using-file-nio-in-java-7/">watching a directory</a> using the new APIs introduced as part of Java 7. In this post let me throw some light on another class added to the java.nio package as part of Java 7 update- <a title="Files" href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" target="_blank">java.nio.file.Files</a>. Another piece of information related to this is that complete java.nio.file package was added as part of Java 7 release. I am not going to write about all the methods in Files class, instead pick few of the methods and compare how we would perform the same operation pre Java 7 with that of using Files API.</p>
<h4>Copying the contents of one file to another</h4>
<p>:<br />
Here&#8217;s how we would do it in before Java 7- using BufferedReader, BufferedWriter.</p>
<pre class="brush: java; title: ; notranslate">
//Before Java 7
BufferedReader reader = null;
BufferedWriter writer = null;
try {

  reader = new BufferedReader(
       new FileReader(&quot;/tmp/nio/file1&quot;));

  writer = new BufferedWriter(
       new FileWriter(&quot;/tmp/nio/file2_old&quot;));
  String dataRead = null;
  while ((dataRead = reader.readLine()) != null) {
    writer.write(dataRead);
    writer.newLine();
  }

} catch (IOException e) {
  System.out.println(&quot;IOException encoutnered&quot;);
} finally {
  if (reader != null) {
    try {
      reader.close();
    } catch (IOException e) {
      System.out.println(&quot;Exception while closing reader&quot;);
    }
  }
  if (writer != null) {
    try {
      writer.close();
    } catch (IOException e) {
      System.out.println(&quot;Exception while closing the writer.&quot;);
    }
  }

}
System.out.println(&quot;File created: &quot; +
          new File(&quot;/tmp/nio/file2_old&quot;).exists());
</pre>
<p>All of you should be familiar with the above code. Now lets see how this can be done using the Files API:</p>
<pre class="brush: java; title: ; notranslate">
//After Java 7
Path source = Paths.get(&quot;/tmp/nio/file1&quot;);
Path target = Paths.get(&quot;/tmp/nio/file2_new&quot;);
try {
  Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
  System.out.println(&quot;Exception while copying usng new API&quot;);
}
System.out.println(&quot;File created: &quot; + Files.exists(target));
</pre>
<p>I know you cannot believe your eyes, that&#8217;s the power of APIs and no wonder Scala has loads of them. Lets have a look at the new classes used above:</p>
<ul>
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html" target="_blank">Path</a>: This is used to represent the location of a file/directory in the file system.</li>
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Paths.html" target="_blank">Paths</a> &#8211; This is the factory class to create instances of Path class.</li>
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" target="_blank">Files</a>- A new class with lots of helper methods to perform operations on File.</li>
</ul>
<p>There are overloaded versions of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy%28java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...%29">copy</a> method which can take an <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy%28java.io.InputStream,%20java.nio.file.Path,%20java.nio.file.CopyOption...%29" target="_blank">InputStream and write to a file</a>, read it from a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy%28java.nio.file.Path,%20java.io.OutputStream%29" target="_blank">file and write to OutputStream</a> or <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy%28java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...%29" target="_blank">read and write to a file</a>. The first 2 help us to choose different source and different destination respectively.</p>
<p>We have used the third variant of the copy method. Apart from the source and target destinations, the copy method also accepts some <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/CopyOption.html" target="_blank">CopyOption</a> which indicate to the copy function whether to replace any existing file among other options which are supported.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h4>Reading all the lines from a file into a List</h4>
<p>:<br />
Lets have a look at the pre Java 7 approach</p>
<pre class="brush: java; title: ; notranslate">
List&lt;String&gt; linesInFile = new ArrayList&lt;String&gt;();
BufferedReader reader2 = null;
try{
  String lineRead = null;
  reader2 = new BufferedReader(new FileReader(&quot;/tmp/nio/file3&quot;));
  while ((lineRead = reader2.readLine()) != null){
    linesInFile.add(lineRead);
  }
} catch (IOException e) {
  System.out.println(&quot;IO error&quot;);
}
System.out.println(&quot;Lines read using old style: &quot;);
for (String s : linesInFile){
  System.out.println(s);
}
</pre>
<p>Pretty straight forward using BufferedReader, but too many unwanted/unrelated code statements.</p>
<p>Lets see how this can be done in using Files API:</p>
<pre class="brush: java; title: ; notranslate">
//In Java 7
Path sourcePath = Paths.get(&quot;/tmp/nio/file3&quot;);
try {
  List&lt;String&gt; linesReadNew =
          Files.readAllLines(sourcePath,
                  Charset.defaultCharset());

  System.out.println(&quot;Lines read using new style:&quot;);
  for(String s : linesReadNew){
    System.out.println(s);
  }
} catch (IOException e) {
  System.out.println(&quot;IO Error&quot;);
}
</pre>
<p>So much more concise than the other approach. And the code is easy to read as well. In this example we make use of the <a title="readAlLLines" href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29" target="_blank">readAllLines</a> method of the Files class. It takes a Path instance indicating which file to read and then uses BufferedReader to read through the file but all this is being taken care of the API.</p>
<p>These were just 2 instances of how the new API made the code more concise and easy to understand. There are lot many such methods in the Files class which create a wrapper over the mundane, repeated code written using File API.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/a-peek-files-utility-part-java-nio-package-java-7/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Implementing WatchService API in Java 7 to monitor the directory changes</title>
		<link>http://www.javabeat.net/2012/06/watchservice-api-java7-monitor-directory/</link>
		<comments>http://www.javabeat.net/2012/06/watchservice-api-java7-monitor-directory/#comments</comments>
		<pubDate>Fri, 15 Jun 2012 19:27:50 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[file nio]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[java 7]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4292</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In Java 7 there were quite a lot of new things added to the File NIO package (java.nio)- there was a new java.nio.file package and java.nio.file.attribute package. Main highlights of the java.nio.file package are the following classes: Path: Its an object used to locate a file or directory in the file system. The value contained [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In Java 7 there were quite a lot of new things added to the File NIO package (java.nio)- there was a new <a href="docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html" title="file nio" target="_blank">java.nio.file</a> package and <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/package-summary.html" target="_blank">java.nio.file.attribute</a> package. Main highlights of the java.nio.file package are the following classes:</p>
<ul>
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html" target="_blank"><strong>Path</strong></a>: Its an object used to locate a file or directory in the file system. The value contained in the Path instance is platform dependent. For example on Windows the file separators would be &#8220;\&#8221; while in a Unix platform it would be &#8220;/&#8221;. </li>
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" title="Files" target="_blank"><strong>Files</strong></a>: This class contains static methods which operate on the Path instance to create files, delete or move the files around and to even get the BufferedReader, BufferedWriter, InputStream, OutputStream among other methods.</li>
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystems.html" target="_blank"><strong>FileSystems</strong></a>: Provides static methods to create instance of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html" target="_blank">FileSystem</a></li>
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html" title="WatchService" target="_blank"><strong>WatchService</strong></a>: A service for watching different locations in the file system for events like modification, creation, deletion. Classes which implement <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Watchable.html" target="_blank">Watchable</a> can be used to register with a watch service. An instance of WatchService can be obtained from the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#newWatchService%28%29" target="_blank">FileSystem</a> instance.</li>
<li><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchKey.html" target="_blank"><strong>WatchKey</strong></a>: When a Watchable entity is registered with a WatchService a key which is a WatchKey is generated. Initially the key is in ready state waiting to be notified of any events on the Watchable entity. Once an event occurs the key goes into signaled state and allows to access the events using its <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchKey.html#pollEvents%28%29" target="_blank">pollEvents</a> method. After processing the poll events the key has to be reset by invoking its <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchKey.html#reset%28%29" target="_blank">reset</a> method.</li>
</ul>
<p>Lets look at an example of watching the &#8220;<strong>/tmp/nio</strong>&#8221; directory (Note: this example was executed on Unix platform, file separator would have to be changed for executing this in Windows platform) for Modification and Deletions happening in the directory.<br />
We first have to create a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html" title="Path" target="_blank"><strong>Path</strong></a> instance to indicate this directory:</p>
<pre class="brush: java; title: ; notranslate">
Path tmpPath = Paths.get(&quot;/tmp/nio/&quot;);
</pre>
<p>Obtain a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html" target="_blank">WatchService</a> from the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html" target="_blank">FileSystem</a> class:</p>
<pre class="brush: java; title: ; notranslate">
WatchService watchService = 
    FileSystems.getDefault().newWatchService();
</pre>
<p>Now we would have to register the Path created above with the WatchService created above and also specify the kind of events we are interested to watch. For the kind of events we make use of <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardWatchEventKinds.html" target="_blank">StandardWatchEventKinds</a> class and its fields ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE. </p>
<pre class="brush: java; title: ; notranslate">

/*
 * Watching the /tmp/nio/ directory
 * for MODIFY and DELETE operations
 */
tmpPath.register(
        watchService,
        StandardWatchEventKinds.ENTRY_MODIFY,
        StandardWatchEventKinds.ENTRY_DELETE);
</pre>
<p>To watch the directory we place all the processing login in an infinite loop (we can also spawn a different thread to watch, but in this example lets keep it simple). And perform the following tasks:<br />
1. Wait for any key to be signaled by invoking the <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html#take%28%29" target="_blank">take()</a> method of the WatchService class. One can even use <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html#poll%28%29" target="_blank">poll()</a> method but the difference is that take() is a blocking call and waits until some key is signaled.<br />
2. Once a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchKey.html" target="_blank">WatchKey</a> is obtained, poll for the events available in the key.<br />
3. For each event find out the type of the event using <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchEvent.Kind.html#type%28%29" target="_blank">event.kind().type()</a> and also the Path which the event is acting on by using <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchEvent.html#context%28%29" target="_blank">event.context()</a> method.</p>
<p>The above 3 steps in code would be:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
/*
 * Keep polling for events on the watched directory,
 */
for(;;){
    WatchKey key = watchService.take();

    //Poll all the events queued for the key
    for ( WatchEvent&lt;?&gt; event: key.pollEvents()){
        WatchEvent.Kind kind = event.kind();
        switch (kind.name()){
            case &quot;ENTRY_MODIFY&quot;:
                System.out.println(&quot;Modified: &quot;+event.context());
                break;
            case &quot;ENTRY_DELETE&quot;:
                System.out.println(&quot;Delete: &quot;+event.context());
                break;
        }
    }
    //reset is invoked to put the key back to ready state
    boolean valid = key.reset();

    //If the key is invalid, just exit.
    if ( !valid){
        break;
    }
}
</pre>
<p>Dont forget to <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchKey.html#reset%28%29" target="_blank">reset()</a> the key once done with handling the events. Otherwise the key would not be in Ready state to listen to more events. </p>
<p>Combining all the parts discussed above, the complete program would be:</p>
<pre class="brush: java; title: ; notranslate">
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.*;

public class DirectoryWatcherDemo {

    public static void main(String[] args) throws 
        URISyntaxException, 
        IOException, 
        InterruptedException {

        Path tmpPath = Paths.get(&quot;/tmp/nio/&quot;);
        WatchService watchService = 
            FileSystems.getDefault().newWatchService();

         //Watching the /tmp/nio/ directory
         //for MODIFY and DELETE operations
        tmpPath.register(
                watchService,
                StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE);

        /*
         * Keep polling for events on the watched directory,
         */
        for(;;){
            WatchKey key = watchService.take();

            //Poll all the events queued for the key
            for ( WatchEvent&lt;?&gt; event: key.pollEvents()){
                WatchEvent.Kind kind = event.kind();
                switch (kind.name()){
                    case &quot;ENTRY_MODIFY&quot;:
                        System.out.println(&quot;Modified: &quot;+event.context());
                        break;
                    case &quot;ENTRY_DELETE&quot;:
                        System.out.println(&quot;Delete: &quot;+event.context());
                        break;
                }
            }
            //reset is invoked to put the key back to ready state
            boolean valid = key.reset();

            //If the key is invalid, just exit.
            if ( !valid){
                break;
            }
        }

    }
}
</pre>
<p>Running the following commands in the terminal in &#8220;/tmp/nio&#8221; directory:</p>
<pre class="brush: bash; title: ; notranslate">
mohamed@mohamed:/tmp/nio$ ls
mohamed@mohamed:/tmp/nio$ touch t1
mohamed@mohamed:/tmp/nio$ touch t2
mohamed@mohamed:/tmp/nio$ touch t3
mohamed@mohamed:/tmp/nio$ rm t1
mohamed@mohamed:/tmp/nio$ vim t2
mohamed@mohamed:/tmp/nio$ mkdir t4
mohamed@mohamed:/tmp/nio$ rm -r t4
mohamed@mohamed:/tmp/nio$ ls
t2  t3
</pre>
<p>results in the following output in the directory watching program:</p>
<pre class="brush: bash; title: ; notranslate">
Modified: t1
Modified: t2
Modified: t3
Delete: t1
Delete: .t2.swpx
Delete: .t2.swp
Modified: .t2.swp
Modified: .t2.swp
Modified: t2
Modified: t2
Delete: .t2.swp
Delete: t4
</pre>
<p>One thing to note here is that we did execute <strong>mkdir t4</strong> to create a t4 directory but that wasn&#8217;t notified because we didn&#8217;t register the ENTRY_CREATE event. Also once the new directory is added one has to register the new directory with the WatchService. I will write about this in a separate post sometime later. </p>
<p>Do drop in your queries or any issues you are facing with the above example and explanation. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/watchservice-api-java7-monitor-directory/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Merge Sort implementation using Fork-Join Framework in Java 7</title>
		<link>http://www.javabeat.net/2012/06/merge-sort-implemented-using-fork-join/</link>
		<comments>http://www.javabeat.net/2012/06/merge-sort-implemented-using-fork-join/#comments</comments>
		<pubDate>Wed, 13 Jun 2012 17:53:28 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[Fork Join]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Merge Sort]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4283</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In our previous post we went through the basics of Fork-Join Framework introduced as part of Java 7. In this post lets apply the same Fork-Join to implement Merge sort algorithm. The pseudo code for Merge sort can be found here. In summary the Merge sort algorithm: 1. Divides the array into 1 parts 2. [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In our <a href="http://www.javabeat.net/2012/06/simple-introduction-to-fork-join-framework-in-java-7/" title="Simple introduction to Fork-Join Framework in Java 7">previous post</a> we went through the basics of Fork-Join Framework introduced as part of Java 7. In this post lets apply the same Fork-Join to implement Merge sort algorithm. The pseudo code for Merge sort can be found <a href="http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/merge/mergen.htm" target="_blank">here</a>.</p>
<p>In summary the Merge sort algorithm:<br />
1. Divides the array into 1 parts<br />
2. Sort each part individually and merge them to form a smaller sorted array.<br />
3. Merge individual sorted arrays to get the complete sorted array. </p>
<p>We create a task for dividing the array into 2 parts and then merge the arrays in the same task (i.e we dont spawn a new task for merging the arrays). </p>
<pre class="brush: java; title: ; notranslate">
class DivideTask extends RecursiveTask&lt;int[]&gt; {

  int[] arrayToDivide;

  public DivideTask(int[] arrayToDivide) {
    this.arrayToDivide = arrayToDivide;
  }

  @Override
  protected int[] compute() {
    List&lt;RecursiveTask&gt; forkedTasks = new ArrayList&lt;&gt;();

    /*
     * We divide the array till it has only 1 element. 
     * We can also custom define this value to say some 
     * 5 elements. In which case the return would be
     * Arrays.sort(arrayToDivide) instead.
     */
    if (arrayToDivide.length &gt; 1) {
      
      List&lt;int[]&gt; partitionedArray = partitionArray();
      
      DivideTask task1 = new DivideTask(partitionedArray.get(0));
      DivideTask task2 = new DivideTask(partitionedArray.get(1));
      invokeAll(task1, task2);
      
      //Wait for results from both the tasks
      int[] array1 = task1.join();
      int[] array2 = task2.join();
      
      //Initialize a merged array
      int[] mergedArray = 
              new int[array1.length + array2.length];
      
      mergeArrays(task1.join(), task2.join(), mergedArray);

      return mergedArray;
    }
    return arrayToDivide;
  }
  
  private List&lt;int[]&gt; partitionArray(){
    
    int [] partition1 = Arrays.copyOfRange(arrayToDivide, 0,
              arrayToDivide.length / 2);
      
    int [] partition2 = Arrays.copyOfRange(arrayToDivide,
              arrayToDivide.length / 2,
              arrayToDivide.length);
    return Arrays.asList(partition1,partition2);
    
  }

  private void mergeArrays(
          int[] array1, 
          int[] array2, 
          int[] mergedArray) {
    
    int i = 0, j = 0, k = 0;
    
    while ((i &lt; array1.length) &amp;&amp; (j &lt; array2.length)) {
    
      if (array1[i] &lt; array2[j]) {
        mergedArray[k] = array1[i++];
      } else {
        mergedArray[k] = array2[j++];
      }
      
      k++;
    }
    
    if (i == array1.length) {
      
      for (int a = j; a &lt; array2.length; a++) {
        mergedArray[k++] = array2[a];
      }
      
    } else {
      
      for (int a = i; a &lt; array1.length; a++) {
        mergedArray[k++] = array1[a];
      }
      
    }
  }
}
</pre>
<p>In the above declared task, we override the compute method to partition the array given to be sorted:</p>
<pre class="brush: java; title: ; notranslate">
int[] arrayPart1 = null;
int[] arrayPart2 = null;
partitionArray(arrayToDivide, arrayPart1, arrayPart2);
</pre>
<p>if the array given to the task cannot be divided further i.e has only one element, then return that array</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
return arrayToDivide;
</pre>
<p>If the partitions were created, then assign each partition to a new task and invoke the tasks created:</p>
<pre class="brush: java; title: ; notranslate">
DivideTask task1 = new DivideTask(arrayPart1);
DivideTask task2 = new DivideTask(arrayPart2);
invokeAll(task1, task2);
</pre>
<p>We would then have to wait for the results from both the tasks spawned and then merge their results to create a smaller sorted array:</p>
<pre class="brush: java; title: ; notranslate">
//Wait for results from both the tasks
int[] array1 = task1.join();
int[] array2 = task2.join();

//Initialize a merged array
int[] mergedArray = 
new int[array1.length + array2.length];

mergeArrays(task1.join(), task2.join(), mergedArray);

return mergedArray;
</pre>
<p>This way each of the task which spawns more sub tasks would wait for their sub tasks to return a sorted array and then return back the sorted array to the parent task. This operation can be invoked as:</p>
<pre class="brush: java; title: ; notranslate">
public class ForkJoinTest {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    
    int totalNumbers = scanner.nextInt();
    
    int[] numbers = new int[totalNumbers];
    
    for (int i = 0; i &lt; totalNumbers; i++) {
      numbers[i] = scanner.nextInt();
    }
    
    System.out.println(&quot;Unsorted array: &quot; 
         + Arrays.toString(numbers));

    DivideTask task = new DivideTask(numbers);
    ForkJoinPool forkJoinPool = new ForkJoinPool();
    forkJoinPool.invoke(task);
    
    System.out.println(&quot;Sorted array: &quot; 
         + Arrays.toString(task.join()));

  }
}
</pre>
<p>Output:</p>
<pre class="brush: bash; title: ; notranslate">
run:
8
8 3 2 9 7 1 5 4
Unsorted array: [8, 3, 2, 9, 7, 1, 5, 4]
Sorted array: [1, 2, 3, 4, 5, 7, 8, 9]
BUILD SUCCESSFUL (total time: 2 seconds)
</pre>
<p>Another useful variant of Merge sort algorithm can be found <a href="http://faculty.ycp.edu/~dhovemey/spring2011/cs365/lecture/lecture18.html" target="_blank">here</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/merge-sort-implemented-using-fork-join/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
