Author: saqibkhan

  • Field 

    Introduction

    The java.lang.reflect.Field class provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field. A Field permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

    Class declaration

    Following is the declaration for java.lang.reflect.Field class −

    public final class Field
       extends AccessibleObject
    
      implements Member

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class methods

    Sr.No.Method & Description
    1boolean equals(Object obj)Compares this Field against the specified object.
    2Object get(Object obj)Returns the value of the field represented by this Field, on the specified object.
    3<T extends Annotation> T getAnnotation(Class<T> annotationClass)Returns this element’s annotation for the specified type if such an annotation is present, else null.
    4boolean getBoolean(Object obj)Gets the value of a static or instance boolean field.
    5byte getByte(Object obj)Gets the value of a static or instance byte field.
    6char getChar(Object obj)Gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion.
    7Annotation[] getDeclaredAnnotations()Returns all annotations that are directly present on this element.
    8Class<?> getDeclaringClass()Returns the Class object representing the class or interface that declares the field represented by this Field object.
    9double getDouble(Object obj)Gets the value of a static or instance field of type double or of another primitive type convertible to type double via a widening conversion.
    10float getFloat(Object obj)Gets the value of a static or instance field of type float or of another primitive type convertible to type float via a widening conversion.
    11Type getGenericType()Returns a Type object that represents the declared type for the field represented by this Field object.
    12int getInt(Object obj)Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion.
    13long getLong(Object obj)Gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion.
    14int getModifiers()Returns the Java language modifiers for the field represented by this Field object, as an integer.
    15String getName()RReturns the name of the field represented by this Field object.
    16short getShort(Object obj)Gets the value of a static or instance field of type short or of another primitive type convertible to type short via a widening conversion.
    17Class<?> getType()Returns a Class object that identifies the declared type for the field represented by this Field object.
    18int hashCode()Returns a hashcode for this Field.
    19boolean isEnumConstant()Returns true if this field represents an element of an enumerated type; returns false otherwise.
    20boolean isSynthetic()This method returns true if the field represented by the current object is synthetic, else it returns false.
    21void setBoolean(Object obj, boolean z)Sets the value of a field as a boolean on the specified object.
    22void setByte(Object obj, byte b)Sets the value of a field as a byte on the specified object.
    23void setChar(Object obj, char c)Sets the value of a field as a char on the specified object.
    24void setDouble(Object obj, double d)Sets the value of a field as a double on the specified object.
    25void setFloat(Object obj, float f)Sets the value of a field as a float on the specified object.
    26void setInt(Object obj, int i)Sets the value of a field as an int on the specified object.
    27void setLong(Object obj, long l)Sets the value of a field as a long on the specified object.
    28void setShort(Object obj, short s)Sets the value of a field as a short on the specified object.
    29String toGenericString()Returns a string describing this Field, including its generic type.
    30String toString()Returns a string describing this Field.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.reflect.AccessibleObject
    • java.lang.Object
  • Constructor

    Introduction

    The java.lang.reflect.Constructor class provides information about, and access to, a single constructor for a class. Constructor permits widening conversions to occur when matching the actual parameters to newInstance() with the underlying constructor’s formal parameters, but throws an IllegalArgumentException if a narrowing conversion would occur.

    Class declaration

    Following is the declaration for java.lang.reflect.Constructor class −

    public final class Constructor<T>
       extends AccessibleObject
    
      implements GenericDeclaration, Member

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class methods

    Sr.No.Method & Description
    1boolean equals(Object obj)Compares this Constructor against the specified object.
    2<T extends Annotation> T getAnnotation(Class<T> annotationClass)Returns this element’s annotation for the specified type if such an annotation is present, else null.
    3Annotation[] getDeclaredAnnotations()Returns all annotations that are directly present on this element.
    4Class<T> getDeclaringClass()Returns the Class object representing the class that declares the constructor represented by this Constructor object.
    5Class<?>[] getExceptionTypes()Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying constructor represented by this Constructor object.
    6Type[] getGenericExceptionTypes()Returns an array of Type objects that represent the exceptions declared to be thrown by this Constructor object.
    7Type[] getGenericParameterTypes()Returns an array of Type objects that represent the formal parameter types, in declaration order, of the method represented by this Constructor object.
    8int getModifiers()Returns the Java language modifiers for the constructor represented by this Constructor object, as an integer.
    9String getName()Returns the name of this constructor, as a string.
    10Annotation[][] getParameterAnnotations()Returns an array of arrays that represent the annotations on the formal parameters, in declaration order, of the method represented by this Constructor object.
    11Class<?>[] getParameterTypes()Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object.
    12int hashCode()Returns a hashcode for this Constructor.
    13boolean isSynthetic()Returns true if this constructor is a synthetic constructor; returns false otherwise.
    14boolean isVarArgs()Returns true if this constructor was declared to take a variable number of arguments; returns false otherwise.
    15T newInstance(Object… initargs)Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor’s declaring class, with the specified initialization parameters.
    16String toGenericString()Returns a string describing this Constructor, including type parameters.
    17String toString()Returns a string describing this Constructor.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.reflect.AccessibleObject
    • java.lang.Object
  • reflect – Array

    Introduction

    The java.lang.reflect.Array class provides static methods to dynamically create and access Java arrays. Array permits widening conversions to occur during a get or set operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

    Class declaration

    Following is the declaration for java.lang.reflect.Array class −

    public final class Array
       extends Object
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class methods

    Sr.No.Method & Description
    1static Object get(Object array, int index)Returns the value of the indexed component in the specified array object.
    2static boolean getBoolean(Object array, int index)Returns the value of the indexed component in the specified array object, as a boolean.
    3static byte getByte(Object array, int index)Returns the value of the indexed component in the specified array object, as a byte.
    4static char getChar(Object array, int index)Returns the value of the indexed component in the specified array object, as a char.
    5static double getDouble(Object array, int index)Returns the value of the indexed component in the specified array object, as a double.
    6static float getFloat(Object array, int index)Returns the value of the indexed component in the specified array object, as a float.
    7static int getInt(Object array, int index)Returns the value of the indexed component in the specified array object, as an int.
    8static int getLength(Object array)Returns the length of the specified array object, as an int.
    9static long getLong(Object array, int index)Returns the value of the indexed component in the specified array object, as a long.
    10static short getShort(Object array, int index)Returns the value of the indexed component in the specified array object, as a short.
    11static Object newInstance(Class<?> componentType, int… dimensions)Creates a new array with the specified component type and dimensions.
    12static Object newInstance(Class<?> componentType, int length)Creates a new array with the specified component type and length.
    13static void set(Object array, int index, Object value)Sets the value of the indexed component of the specified array object to the specified new value.
    14static void setBoolean(Object array, int index, boolean z)Sets the value of the indexed component of the specified array object to the specified boolean value.
    15static void setByte(Object array, int index, byte b)Sets the value of the indexed component of the specified array object to the specified byte value.
    16static void setChar(Object array, int index, char c)Sets the value of the indexed component of the specified array object to the specified char value.
    17static void setDouble(Object array, int index, double d)Sets the value of the indexed component of the specified array object to the specified double value.
    18static void setFloat(Object array, int index, float f)Sets the value of the indexed component of the specified array object to the specified float value.
    19static void setInt(Object array, int index, int i)Sets the value of the indexed component of the specified array object to the specified int value.
    20static void setLong(Object array, int index, long l)Sets the value of the indexed component of the specified array object to the specified long value.
    21static void setShort(Object array, int index, short s)Sets the value of the indexed component of the specified array object to the specified short value.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.Object
  • AccessibleObject 

    Introduction

    The java.lang.reflect.AccessibleObject class is the base class for Field, Method and Constructor objects. It provides the ability to flag a reflected object as suppressing default Java language access control checks when it is used. The access checks for public, default (package) access, protected, and private members are performed when Fields, Methods or Constructors are used to set or get fields, to invoke methods, or to create and initialize new instances of classes, respectively. Setting the accessible flag in a reflected object permits sophisticated applications with sufficient privilege, such as Java Object Serialization or other persistence mechanisms, to manipulate objects in a manner that would normally be prohibited.

    Class declaration

    Following is the declaration for java.lang.reflect.AccessibleObject class −

    public class AccessibleObject
       extends Object
    
      implements AnnotatedElement

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Constructors

    Sr.No.Constructor & Description
    1protected AccessibleObject()Constructor: only used by the Java Virtual Machine.

    Class methods

    Sr.No.Method & Description
    1<T extends Annotation> T getAnnotation(Class<T> annotationClass)Returns this element’s annotation for the specified type if such an annotation is present, else null.
    2Annotation[] getAnnotations()Returns all annotations present on this element.
    3Annotation[] getDeclaredAnnotations()Returns all annotations that are directly present on this element.
    4boolean isAccessible()Get the value of the accessible flag for this object.
    5boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)Returns true if an annotation for the specified type is present on this element, else false.
    6static void setAccessible(AccessibleObject[] array, boolean flag)Convenience method to set the accessible flag for an array of objects with a single security check (for efficiency).
    7void setAccessible(boolean flag)Set the accessible flag for this object to the indicated boolean value.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.Object
  • FileLock

    As we know that Java NIO supports concurrency and multi threading which enables it to deal with the multiple threads operating on multiple files at same time.But in some cases we require that our file would not get share by any of thread and get non accessible.

    For such requirement NIO again provides an API known as FileLock which is used to provide lock over whole file or on a part of file,so that file or its part doesn’t get shared or accessible.

    in order to provide or apply such lock we have to use FileChannel or AsynchronousFileChannel,which provides two methods lock() and tryLock()for this purpose.The lock provided may be of two types −

    • Exclusive Lock − An exclusive lock prevents other programs from acquiring an overlapping lock of either type.
    • Shared Lock − A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks.

    Methods used for obtaining lock over file −

    • lock() − This method of FileChannel or AsynchronousFileChannel acquires an exclusive lock over a file associated with the given channel.Return type of this method is FileLock which is further used for monitoring the obtained lock.
    • lock(long position, long size, boolean shared) − This method again is the overloaded method of lock method and is used to lock a particular part of a file.
    • tryLock() − This method return a FileLock or a null if the lock could not be acquired and it attempts to acquire an explicitly exclusive lock on this channel’s file.
    • tryLock(long position, long size, boolean shared) − This method attempts to acquires a lock on the given region of this channel’s file which may be an exclusive or of shared type.

    Methods of FileLock Class

    • acquiredBy() − This method returns the channel on whose file lock was acquired.
    • position() − This method returns the position within the file of the first byte of the locked region.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file’s current size.
    • size() − This method returns the size of the locked region in bytes.A locked region need not be contained within, or even overlap, the actual underlying file, so the value returned by this method may exceed the file’s current size.
    • isShared() − This method is used to determine that whether lock is shared or not.
    • overlaps(long position,long size) − This method tells whether or not this lock overlaps the given lock range.
    • isValid() − This method tells whether or not the obtained lock is valid.A lock object remains valid until it is released or the associated file channel is closed, whichever comes first.
    • release() − Releases the obtained lock.If the lock object is valid then invoking this method releases the lock and renders the object invalid. If this lock object is invalid then invoking this method has no effect.
    • close() − This method invokes the release() method. It was added to the class so that it could be used in conjunction with the automatic resource management block construct.

    Example to demonstrate file lock.

    Following example create lock over a file and write content to it

    package com.java.nio;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.channels.FileLock;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
    public class FileLockExample {
       public static void main(String[] args) throws IOException {
    
      String input = "Demo text to be written in locked mode.";  
      System.out.println("Input string to the test file is: " + input);  
      ByteBuffer buf = ByteBuffer.wrap(input.getBytes());  
      String fp = "D:file.txt";  
      Path pt = Paths.get(fp);  
      FileChannel channel = FileChannel.open(pt, StandardOpenOption.WRITE,StandardOpenOption.APPEND);  
      channel.position(channel.size() - 1); // position of a cursor at the end of file       
      FileLock lock = channel.lock();   
      System.out.println("The Lock is shared: " + lock.isShared());  
      channel.write(buf);  
      channel.close(); // Releases the Lock  
      System.out.println("Content Writing is complete. Therefore close the channel and release the lock.");  
      PrintFileCreated.print(fp);  
    } }
    package com.java.nio;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    public class PrintFileCreated {
       public static void print(String path) throws IOException {  
    
      FileReader filereader = new FileReader(path);  
      BufferedReader bufferedreader = new BufferedReader(filereader);  
      String tr = bufferedreader.readLine();    
      System.out.println("The Content of testout.txt file is: ");  
      while (tr != null) {      
         System.out.println("    " + tr);  
         tr = bufferedreader.readLine();  
      }  
    filereader.close(); bufferedreader.close(); } }

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Output

    Input string to the test file is: Demo text to be written in locked mode.
    The Lock is shared: false
    Content Writing is complete. Therefore close the channel and release the lock.
    The Content of testout.txt file is: 
    To be or not to be?Demo text to be written in locked mode.
    
  • CharSet

    In Java for every character there is a well defined unicode code units which is internally handled by JVM.So Java NIO package defines an abstract class named as Charset which is mainly used for encoding and decoding of charset and UNICODE.

    Standard charsets

    The supported Charset in java are given below.

    • US-ASCII − Seven bit ASCII characters.
    • ISO-8859-1 − ISO Latin alphabet.
    • UTF-8 − This is 8 bit UCS transformation format.
    • UTF-16BE − This is 16 bit UCS transformation format with big endian byte order.
    • UTF-16LE − This is 16 bit UCS transformation with little endian byte order.
    • UTF-16 − 16 bit UCS transformation format.

    Important methods of Charset class

    • forName() − This method creates a charset object for the given charset name.The name can be canonical or an alias.
    • displayName() − This method returns the canonical name of given charset.
    • canEncode() − This method checks whether the given charset supports encoding or not.
    • decode() − This method decodes the string of a given charset into charbuffer of Unicode charset.
    • encode() − This method encodes charbuffer of unicode charset into the byte buffer of given charset.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Example

    Following example illustrate important methods of Charset class.

    package com.java.nio;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.charset.Charset;
    public class CharsetExample {
       public static void main(String[] args) {
    
      Charset charset = Charset.forName("US-ASCII");
      System.out.println(charset.displayName());
      System.out.println(charset.canEncode());
      String str= "Demo text for conversion.";
      //convert byte buffer in given charset to char buffer in unicode
      ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
      CharBuffer charBuffer = charset.decode(byteBuffer);
      //convert char buffer in unicode to byte buffer in given charset
      ByteBuffer newByteBuffer = charset.encode(charBuffer);
      while(newbb.hasRemaining()){
         char ch = (char) newByteBuffer.get();
         System.out.print(ch);
      }
      newByteBuffer.clear();
    } }

    Output

    US-ASCII
    Demo text for conversion.
    
  • AsynchronousFileChannel

    As we know that Java NIO supports concurrency and multi-threading which allows us to deal with different channels concurrently at same time.So the API which is responsible for this in Java NIO package is AsynchronousFileChannel which is defined under NIO channels package.Hence qualified name for AsynchronousFileChannel is java.nio.channels.AsynchronousFileChannel.

    AsynchronousFileChannel is similar to that of the NIO’s FileChannel,except that this channel enables file operations to execute asynchronously unlike of synchronous I/O operation in which a thread enters into an action and waits until the request is completed.Thus asynchronous channels are safe for use by multiple concurrent threads.

    In asynchronous the request is passed by thread to the operating system’s kernel to get it done while thread continues to process another job.Once the job of kernel is done it signals the thread then the thread acknowledged the signal and interrupts the current job and processes the I/O job as needed.

    For achieving concurrency this channel provides two approaches which includes one as returning a java.util.concurrent.Future object and other is Passing to the operation an object of type java.nio.channels.CompletionHandler.

    We will understand both the approaches with help of examples one by one.

    • Future Object − In this an instance of Future Interface is returned from channel.In Future interface there is get() method which returns the status of operation that is handled asynchronously on the basis of which further execution of other task could get decided.We can also check whether task is completed or not by calling its isDone method.

    Example

    The following example shows the how to use Future object and to task asynchronously.

    package com.java.nio;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.AsynchronousFileChannel;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Future;
    
    public class FutureObject {
       public static void main(String[] args) throws Exception {
    
      readFile();
    } private static void readFile() throws IOException, InterruptedException, ExecutionException {
      String filePath = "D:fileCopy.txt";
      printFileContents(filePath);
      Path path = Paths.get(filePath);		
      AsynchronousFileChannel channel =AsynchronousFileChannel.open(path, StandardOpenOption.READ);
      ByteBuffer buffer = ByteBuffer.allocate(400);
      Future&lt;Integer&gt; result = channel.read(buffer, 0); // position = 0
      while (! result.isDone()) {
         System.out.println("Task of reading file is in progress asynchronously.");
      }
      System.out.println("Reading done: " + result.isDone());
      System.out.println("Bytes read from file: " + result.get()); 
      buffer.flip();
      System.out.print("Buffer contents: ");
      while (buffer.hasRemaining()) {
         System.out.print((char) buffer.get());                
      }
      System.out.println(" ");
      buffer.clear();
      channel.close();
    } private static void printFileContents(String path) throws IOException {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      String textRead = br.readLine();
      System.out.println("File contents: ");
      while (textRead != null) {
         System.out.println("     " + textRead);
         textRead = br.readLine();
      }
    fr.close(); br.close(); } }

    Output

    File contents: 
       To be or not to be?
       Task of reading file is in progress asynchronously.
       Task of reading file is in progress asynchronously.
       Reading done: true
       Bytes read from file: 19
       Buffer contents: To be or not to be? 
    
    • Completion Handler −This approach is pretty simple as in this we uses CompletionHandler interface and overrides its two methods one is completed() method which is invoked when the I/O operation completes successfully and other is failed() method which is invoked if the I/O operations fails.In this a handler is created for consuming the result of an asynchronous I/O operation as once a task is completed then only the handler has functions that are executed.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Example

    The following example shows the how to use CompletionHandler to task asynchronously.

    package com.java.nio;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.AsynchronousFileChannel;
    import java.nio.channels.CompletionHandler;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
    
    public class CompletionHandlerDemo {
       public static void main (String [] args) throws Exception {
    
      writeFile();
    } private static void writeFile() throws IOException {
      String input = "Content to be written to the file.";
      System.out.println("Input string: " + input);
      byte &#91;] byteArray = input.getBytes();
      ByteBuffer buffer = ByteBuffer.wrap(byteArray);
      Path path = Paths.get("D:fileCopy.txt");
      AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
      CompletionHandler handler = new CompletionHandler() {
         @Override
         public void completed(Object result, Object attachment) {
            System.out.println(attachment + " completed and " + result + " bytes are written.");
         }
         @Override
         public void failed(Throwable exc, Object attachment) {
            System.out.println(attachment + " failed with exception:");
            exc.printStackTrace();
         }
      };
      channel.write(buffer, 0, "Async Task", handler);
      channel.close();
      printFileContents(path.toString());
    } private static void printFileContents(String path) throws IOException {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      String textRead = br.readLine();
      System.out.println("File contents: ");
      while (textRead != null) {
         System.out.println("     " + textRead);
         textRead = br.readLine();
      }
      fr.close();
      br.close();
    } }

    Output

    Input string: Content to be written to the file.
    Async Task completed and 34 bytes are written.
    File contents: 
    Content to be written to the file.
    
  • File

    Java NIO package provide one more utility API named as Files which is basically used for manipulating files and directories using its static methods which mostly works on Path object.

    As mentioned in Path tutorial that Path interface is introduced in Java NIO package during Java 7 version in file package.So this tutorial is for same File package.

    This class consists exclusively of static methods that operate on files, directories, or other types of files.In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.

    There are many methods defined in the Files class which could also be read from Java docs.In this tutorial we tried to cover some of the important methods among all of the methods of Java NIO Files class.

    Important methods of Files class.

    Following are the important methods defined in Java NIO Files class.

    • createFile(Path filePath, FileAttribute attrs) − Files class provides this method to create file using specified Path.

    Example

    package com.java.nio;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    public class CreateFile {
       public static void main(String[] args) {
    
      //initialize Path object
      Path path = Paths.get("D:file.txt");
      //create file
      try {
         Path createdFilePath = Files.createFile(path);
         System.out.println("Created a file at : "+createdFilePath);
      } 
      catch (IOException e) {
         e.printStackTrace();
      }
    } }

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Output

    Created a file at : D:\data\file.txt
    
    • copy(InputStream in, Path target, CopyOption� options) − This method is used to copies all bytes from specified input stream to specified target file and returns number of bytes read or written as long value.LinkOption for this parameter with the following values −
      • COPY_ATTRIBUTES − copy attributes to the new file, e.g. last-modified-time attribute.
      • REPLACE_EXISTING − replace an existing file if it exists.
      • NOFOLLOW_LINKS − If a file is a symbolic link, then the link itself, not the target of the link, is copied.

    Example

    package com.java.nio;
    import java.io.IOException;
    import java.nio.charset.Charset;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardCopyOption;
    import java.util.List;
    public class WriteFile {
       public static void main(String[] args) {
    
      Path sourceFile = Paths.get("D:file.txt");
      Path targetFile = Paths.get("D:fileCopy.txt");
      try {
         Files.copy(sourceFile, targetFile,
         StandardCopyOption.REPLACE_EXISTING);
      }
      catch (IOException ex) {
         System.err.format("I/O Error when copying file");
      }
      Path wiki_path = Paths.get("D:fileCopy.txt");
      Charset charset = Charset.forName("ISO-8859-1");
      try {
         List&lt;String&gt; lines = Files.readAllLines(wiki_path, charset);
         for (String line : lines) {
            System.out.println(line);
         }
      } 
      catch (IOException e) {
         System.out.println(e);
      }
    } }

    Output

    To be or not to be?
    
    • createDirectories(Path dir, FileAttribute<?>…attrs) − This method is used to create directories using given path by creating all nonexistent parent directories.
    • delete(Path path) − This method is used to deletes the file from specified path.It throws NoSuchFileException if the file is not exists at specified path or if the file is directory and it may not empty and cannot be deleted.
    • exists(Path path) − This method is used to check if file exists at specified path and if the file exists it will return true or else it returns false.
    • readAllBytes(Path path) − This method is used to reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file.

    Example

    package com.java.nio;
    import java.io.IOException;
    import java.nio.charset.Charset;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.List;
    public class ReadFile {
       public static void main(String[] args) {
    
      Path wiki_path = Paths.get("D:file.txt");
      Charset charset = Charset.forName("ISO-8859-1");
      try {
         List&lt;String&gt; lines = Files.readAllLines(wiki_path, charset);
         for (String line : lines) {
            System.out.println(line);
         }
      } 
      catch (IOException e) {
         System.out.println(e);
      }
    } }

    Output

    Welcome to file.
    
    • size(Path path) − This method is used to get the size of the file at specified path in bytes.
    • write(Path path, byte[] bytes, OpenOption� options) − This method is used to writes bytes to a file at specified path.

    Example

    package com.java.nio;
    import java.io.IOException;
    import java.nio.charset.Charset;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.List;
    public class WriteFile {
       public static void main(String[] args) {
    
      Path path = Paths.get("D:file.txt");
      String question = "To be or not to be?";
      Charset charset = Charset.forName("ISO-8859-1");
      try {
         Files.write(path, question.getBytes());
         List&lt;String&gt; lines = Files.readAllLines(path, charset);
         for (String line : lines) {
            System.out.println(line);
         }
      } 
      catch (IOException e) {
         System.out.println(e);
      }
    } }

    Output

    To be or not to be?
    
  • Path

    As name suggests Path is the particular location of an entity such as file or a directory in a file system so that one can search and access it at that particular location.

    Technically in terms of Java, Path is an interface which is introduced in Java NIO file package during Java version 7,and is the representation of location in particular file system.As path interface is in Java NIO package so it get its qualified name as java.nio.file.Path.

    In general path of an entity could be of two types one is absolute path and other is relative path.As name of both paths suggests that absolute path is the location address from the root to the entity where it locates while relative path is the location address which is relative to some other path.Path uses delimiters in its definition as “\” for Windows and “/” for unix operating systems.

    In order to get the instance of Path we can use static method of java.nio.file.Paths class get().This method converts a path string, or a sequence of strings that when joined form a path string, to a Path instance.This method also throws runtime InvalidPathException if the arguments passed contains illegal characters.

    As mentioned above absolute path is retrieved by passing root element and the complete directory list required to locate the file.While relative path could be retrieved by combining the base path with the relative path.Retrieval of both paths would be illustrated in following example

    Example

    package com.java.nio;
    import java.io.IOException;
    import java.nio.Buffer;
    import java.nio.ByteBuffer;
    import java.nio.file.FileSystem;
    import java.nio.file.LinkOption;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    public class PathDemo {
       public static void main(String[] args) throws IOException {
    
      Path relative = Paths.get("file2.txt");
      System.out.println("Relative path: " + relative);
      Path absolute = relative.toAbsolutePath();
      System.out.println("Absolute path: " + absolute);
    } }

    So far we know that what is path interface why do we need that and how could we access it.Now we would know what are the important methods which Path interface provide us.

    Important methods of Path Interface

    • getFileName() − Returns the file system that created this object.
    • getName() − Returns a name element of this path as a Path object.
    • getNameCount() − Returns the number of name elements in the path.
    • subpath() − Returns a relative Path that is a subsequence of the name elements of this path.
    • getParent() − Returns the parent path, or null if this path does not have a parent.
    • getRoot() − Returns the root component of this path as a Path object, or null if this path does not have a root component.
    • toAbsolutePath() − Returns a Path object representing the absolute path of this path.
    • toRealPath() − Returns the real path of an existing file.
    • toFile() − Returns a File object representing this path.
    • normalize() − Returns a path that is this path with redundant name elements eliminated.
    • compareTo(Path other) − Compares two abstract paths lexicographically.This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument.
    • endsWith(Path other) − Tests if this path ends with the given path.If the given path has N elements, and no root component, and this path has N or more elements, then this path ends with the given path if the last N elements of each path, starting at the element farthest from the root, are equal.
    • endsWith(String other) − Tests if this path ends with a Path, constructed by converting the given path string, in exactly the manner specified by the endsWith(Path) method.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Example

    Following example illustartes the different methods of Path interface which are mentioned above −

    package com.java.nio;
    import java.io.IOException;
    import java.nio.Buffer;
    import java.nio.ByteBuffer;
    import java.nio.file.FileSystem;
    import java.nio.file.LinkOption;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    public class PathDemo {
       public static void main(String[] args) throws IOException {
    
      Path path = Paths.get("D:/workspace/ContentW/Saurav_CV.docx");
      FileSystem fs =  path.getFileSystem();
      System.out.println(fs.toString());
      System.out.println(path.isAbsolute());
      System.out.println(path.getFileName());
      System.out.println(path.toAbsolutePath().toString());
      System.out.println(path.getRoot());
      System.out.println(path.getParent());
      System.out.println(path.getNameCount());
      System.out.println(path.getName(0));
      System.out.println(path.subpath(0, 2));
      System.out.println(path.toString());
      System.out.println(path.getNameCount());
      Path realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
      System.out.println(realPath.toString());
      String originalPath = "d:\\data\\projects\\a-project\\..\\another-project";
      Path path1 = Paths.get(originalPath);
      Path path2 = path1.normalize();
      System.out.println("path2 = " + path2);
    } }
  • Pipe

    In Java NIO pipe is a component which is used to write and read data between two threads.Pipe mainly consist of two channels which are responsible for data propagation.

    Among two constituent channels one is called as Sink channel which is mainly for writing data and other is Source channel whose main purpose is to read data from Sink channel.

    Data synchronization is kept in order during data writing and reading as it must be ensured that data must be read in a same order in which it is written to the Pipe.

    It must kept in notice that it is a unidirectional flow of data in Pipe i.e data is written in Sink channel only and could only be read from Source channel.

    In Java NIO pipe is defined as a abstract class with mainly three methods out of which two are abstract.

    Methods of Pipe class

    • open() − This method is used get an instance of Pipe or we can say pipe is created by calling out this method.
    • sink() − This method returns the Pipe’s sink channel which is used to write data by calling its write method.
    • source() − This method returns the Pipe’s source channel which is used to read data by calling its read method.

    Example

    The following example shows the implementation of Java NIO pipe.

    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.Pipe;
    
    public class PipeDemo {
       public static void main(String[] args) throws IOException {
    
      //An instance of Pipe is created
      Pipe pipe = Pipe.open();
      // gets the pipe's sink channel
      Pipe.SinkChannel skChannel = pipe.sink();
      String testData = "Test Data to Check java NIO Channels Pipe.";
      ByteBuffer buffer = ByteBuffer.allocate(512);
      buffer.clear();
      buffer.put(testData.getBytes());
      buffer.flip();
      //write data into sink channel.
      while(buffer.hasRemaining()) {
         skChannel.write(buffer);
      }
      //gets  pipe's source channel
      Pipe.SourceChannel sourceChannel = pipe.source();
      buffer = ByteBuffer.allocate(512);
      //write data into console     
      while(sourceChannel.read(buffer) &gt; 0){
         //limit is set to current position and position is set to zero
         buffer.flip();
         while(buffer.hasRemaining()){
            char ch = (char) buffer.get();
            System.out.print(ch);
         }
         //position is set to zero and limit is set to capacity to clear the buffer.
         buffer.clear();
      }
    } }

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Output

    Test Data to Check java NIO Channels Pipe.
    

    Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program.