Java NIO – AsynchronousFileChannel ”; Previous Next 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<Integer> 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. 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 [] 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. Print Page Previous Next Advertisements ”;
Category: java Nio
Java NIO – Gather
Java NIO – Gather ”; Previous Next As we know that Java NIO is a more optimized API for data IO operations as compared to the conventional IO API of Java.One more additional support which Java NIO provides is to read/write data from/to multiple buffers to channel.This multiple read and write support is termed as Scatter and Gather in which data is scattered to multiple buffers from single channel in case of read data while data is gathered from multiple buffers to single channel in case of write data. In order to achieve this multiple read and write from channel there is ScatteringByteChannel and GatheringByteChannel API which Java NIO provides for read and write the data as illustrate in below example. GatheringByteChannel write to multiple channels − In this we made to write data from multiple buffers into a single channel.For this again multiple buffers are allocated and are added to a buffer type array.Then this array is passed as parameter to the GatheringByteChannel write() method which then writes data from the multiple buffers in the sequence the buffers occur in the array.One point to remember here is only the data between the position and the limit of the buffers are written. The following example shows how data gathering is performed in Java NIO import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.GatheringByteChannel; public class GatherExample { private static String FILENAME = “C:/Test/temp.txt”; public static void main(String[] args) { String stream1 = “Gather data stream first”; String stream2 = “Gather data stream second”; ByteBuffer bLen1 = ByteBuffer.allocate(1024); ByteBuffer bLen2 = ByteBuffer.allocate(1024); // Next two buffer hold the data we want to write ByteBuffer bstream1 = ByteBuffer.wrap(stream1.getBytes()); ByteBuffer bstream2 = ByteBuffer.wrap(stream2.getBytes()); int len1 = stream1.length(); int len2 = stream2.length(); // Writing length(data) to the Buffer bLen1.asIntBuffer().put(len1); bLen2.asIntBuffer().put(len2); System.out.println(“Gathering : Len1 = ” + len1); System.out.println(“Gathering : Len2 = ” + len2); // Write data to the file try { FileOutputStream out = new FileOutputStream(FILENAME); GatheringByteChannel gather = out.getChannel(); gather.write(new ByteBuffer[] {bLen1, bLen2, bstream1, bstream2}); out.close(); gather.close(); } catch (FileNotFoundException exObj) { exObj.printStackTrace(); } catch(IOException ioObj) { ioObj.printStackTrace(); } } } Output Gathering : Len1 = 24 Gathering : Len2 = 25 In last it can be concluded that scatter/gather approach in Java NIO is introduced as an optimized and multitasked when used properly.It allows you to delegate to the operating system the grunt work of separating out the data you read into multiple buckets, or assembling disparate chunks of data into a whole.No doubt this saves time and uses operating system more efficiently by avoiding buffer copies, and reduces the amount of code need to write and debug. Print Page Previous Next Advertisements ”;
Java NIO – FileLock
Java NIO – FileLock ”; Previous Next 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(); } } 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. Print Page Previous Next Advertisements ”;
Java NIO – File Channel
Java NIO – File Channel ”; Previous Next Description As already mentioned FileChannel implementation of Java NIO channel is introduced to access meta data properties of the file including creation, modification, size etc.Along with this File Channels are multi threaded which again makes Java NIO more efficient than Java IO. In general we can say that FileChannel is a channel that is connected to a file by which you can read data from a file, and write data to a file.Other important characteristic of FileChannel is this that it cannot be set into non-blocking mode and always runs in blocking mode. We can”t get file channel object directly, Object of file channel is obtained either by − getChannel() − method on any either FileInputStream, FileOutputStream or RandomAccessFile. open() − method of File channel which by default open the channel. The object type of File channel depends on type of class called from object creation i.e if object is created by calling getchannel method of FileInputStream then File channel is opened for reading and will throw NonWritableChannelException in case attempt to write to it. Example The following example shows the how to read and write data from Java NIO FileChannel. Following example reads from a text file from C:/Test/temp.txt and prints the content to the console. temp.txt Hello World! FileChannelDemo.java import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.HashSet; import java.util.Set; public class FileChannelDemo { public static void main(String args[]) throws IOException { //append the content to existing file writeFileChannel(ByteBuffer.wrap(“Welcome to TutorialsPoint”.getBytes())); //read the file readFileChannel(); } public static void readFileChannel() throws IOException { RandomAccessFile randomAccessFile = new RandomAccessFile(“C:/Test/temp.txt”, “rw”); FileChannel fileChannel = randomAccessFile.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(512); Charset charset = Charset.forName(“US-ASCII”); while (fileChannel.read(byteBuffer) > 0) { byteBuffer.rewind(); System.out.print(charset.decode(byteBuffer)); byteBuffer.flip(); } fileChannel.close(); randomAccessFile.close(); } public static void writeFileChannel(ByteBuffer byteBuffer)throws IOException { Set<StandardOpenOption> options = new HashSet<>(); options.add(StandardOpenOption.CREATE); options.add(StandardOpenOption.APPEND); Path path = Paths.get(“C:/Test/temp.txt”); FileChannel fileChannel = FileChannel.open(path, options); fileChannel.write(byteBuffer); fileChannel.close(); } } Output Hello World! Welcome to TutorialsPoint Print Page Previous Next Advertisements ”;
Java NIO – Path
Java NIO – Path ”; Previous Next 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. 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); } } Print Page Previous Next Advertisements ”;
Java NIO – Scatter
Java NIO – Scatter ”; Previous Next As we know that Java NIO is a more optimized API for data IO operations as compared to the conventional IO API of Java.One more additional support which Java NIO provides is to read/write data from/to multiple buffers to channel.This multiple read and write support is termed as Scatter and Gather in which data is scattered to multiple buffers from single channel in case of read data while data is gathered from multiple buffers to single channel in case of write data. In order to achieve this multiple read and write from channel there is ScatteringByteChannel and GatheringByteChannel API which Java NIO provides for read and write the data as illustrate in below example. ScatteringByteChannel Read from multiple channels − In this we made to reads data from a single channel into multiple buffers.For this multiple buffers are allocated and are added to a buffer type array.Then this array is passed as parameter to the ScatteringByteChannel read() method which then writes data from the channel in the sequence the buffers occur in the array.Once a buffer is full, the channel moves on to fill the next buffer. The following example shows how scattering of data is performed in Java NIO C:/Test/temp.txt Hello World! import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ScatteringByteChannel; public class ScatterExample { private static String FILENAME = “C:/Test/temp.txt”; public static void main(String[] args) { ByteBuffer bLen1 = ByteBuffer.allocate(1024); ByteBuffer bLen2 = ByteBuffer.allocate(1024); FileInputStream in; try { in = new FileInputStream(FILENAME); ScatteringByteChannel scatter = in.getChannel(); scatter.read(new ByteBuffer[] {bLen1, bLen2}); bLen1.position(0); bLen2.position(0); int len1 = bLen1.asIntBuffer().get(); int len2 = bLen2.asIntBuffer().get(); System.out.println(“Scattering : Len1 = ” + len1); System.out.println(“Scattering : Len2 = ” + len2); } catch (FileNotFoundException exObj) { exObj.printStackTrace(); } catch (IOException ioObj) { ioObj.printStackTrace(); } } } Output Scattering : Len1 = 1214606444 Scattering : Len2 = 0 In last it can be concluded that scatter/gather approach in Java NIO is introduced as an optimized and multitasked when used properly.It allows you to delegate to the operating system the grunt work of separating out the data you read into multiple buckets, or assembling disparate chunks of data into a whole.No doubt this saves time and uses operating system more efficiently by avoiding buffer copies, and reduces the amount of code need to write and debug. Print Page Previous Next Advertisements ”;
Java NIO – Channels
Java NIO – Channels ”; Previous Next Description As name suggests channel is used as mean of data flow from one end to other.Here in java NIO channel act same between buffer and an entity at other end in other words channel are use to read data to buffer and also write data from buffer. Unlike from streams which are used in conventional Java IO channels are two way i.e can read as well as write.Java NIO channel supports asynchronous flow of data both in blocking and non blocking mode. Implementations of Channel Java NIO channel is implemented primarily in following classes − FileChannel − In order to read data from file we uses file channel. Object of file channel can be created only by calling the getChannel() method on file object as we can”t create file object directly. DatagramChannel − The datagram channel can read and write the data over the network via UDP (User Datagram Protocol).Object of DataGramchannel can be created using factory methods. SocketChannel − The SocketChannel channel can read and write the data over the network via TCP (Transmission Control Protocol). It also uses the factory methods for creating the new object. ServerSocketChannel − The ServerSocketChannel read and write the data over TCP connections, same as a web server. For every incoming connection a SocketChannel is created. Example Following example reads from a text file from C:/Test/temp.txt and prints the content to the console. temp.txt Hello World! ChannelDemo.java import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class ChannelDemo { public static void main(String args[]) throws IOException { RandomAccessFile file = new RandomAccessFile(“C:/Test/temp.txt”, “r”); FileChannel fileChannel = file.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(512); while (fileChannel.read(byteBuffer) > 0) { // flip the buffer to prepare for get operation byteBuffer.flip(); while (byteBuffer.hasRemaining()) { System.out.print((char) byteBuffer.get()); } } file.close(); } } Output Hello World! Print Page Previous Next Advertisements ”;
Java NIO – Environment Setup
Java NIO – Environment Setup ”; Previous Next This section guides you on how to download and set up Java on your machine. Please follow the following steps to set up the environment. Java SE is freely available from the link Download Java. So you download a version based on your operating system. Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories − Setting up the path for windows 2000/XP Assuming you have installed Java in c:Program Filesjavajdk directory − Right-click on ”My Computer” and select ”Properties”. Click on the ”Environment variables” button under the ”Advanced” tab. Now alter the ”Path” variable so that it also contains the path to the Java executable. Example, if the path is currently set to ”C:WINDOWSSYSTEM32”, then change your path to read ”C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin”. Setting up the path for windows 95/98/ME Assuming you have installed Java in c:Program Filesjavajdk directory − Edit the ”C:autoexec.bat” file and add the following line at the end: ”SET PATH = %PATH%;C:Program Filesjavajdkbin” Setting up the path for Linux, UNIX, Solaris, FreeBSD Environment variable PATH should be set to point to where the java binaries have been installed. Refer to your shell documentation if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end of your ”.bashrc: export PATH = /path/to/java:$PATH” Popular Java Editors To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following − Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans − is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html. Eclipse − is also a java IDE developed by the eclipse open source community and can be downloaded from https://www.eclipse.org/. Print Page Previous Next Advertisements ”;
Java NIO – Socket Channel
Java NIO – Socket Channel ”; Previous Next Java NIO socket channel is a selectable type channel which means it can be multiplexed using selector, used for stream oriented data flow connecting sockets.Socket channel can be created by invoking its static open() method,providing any pre-existing socket is not already present.Socket channel is created by invoking open method but not yet connected.In order to connect socket channel connect() method is to be called.One point to be mentioned here is if channel is not connected and any I/O operation is tried to be attempted then NotYetConnectedException is thrown by this channel.So one must be ensure that channel is connected before performing any IO operation.Once channel is get connected,it remains connected until it is closed.The state of socket channel may be determined by invoking its isConnected method. The connection of socket channel could be finished by invoking its finishConnect() method.Whether or not a connection operation is in progress may be determined by invoking the isConnectionPending method.By default socket channel supports non-blocking connection.Also it support asynchronous shutdown, which is similar to the asynchronous close operation specified in the Channel class. Socket channels are safe for use by multiple concurrent threads. They support concurrent reading and writing, though at most one thread may be reading and at most one thread may be writing at any given time. The connect and finishConnect methods are mutually synchronized against each other, and an attempt to initiate a read or write operation while an invocation of one of these methods is in progress will block until that invocation is complete. Important methods of Socket channel bind(SocketAddress local) − This method is used to bind the socket channel to the local address which is provided as the parameter to this method. connect(SocketAddress remote) − This method is used to connect the socket to the remote address. finishConnect() − This method is used to finishes the process of connecting a socket channel. getRemoteAddress() − This method return the address of remote location to which the channel”s socket is connected. isConnected() − As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not. open() and open((SocketAddress remote) − Open method is used open a socket channel for no specified address while parameterized open method open channel for specified remote address and also connects to it.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting socket channel, passing it remote, and then returning that channel. read(ByteBuffer dst) − This method is used to read data from the given buffer through socket channel. isConnectionPending() − This method tells whether or not a connection operation is in progress on this channel. Example The following example shows the how to send data from Java NIO SocketChannel. C:/Test/temp.txt Hello World! Client: SocketChannelClient.java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.EnumSet; public class SocketChannelClient { public static void main(String[] args) throws IOException { ServerSocketChannel serverSocket = null; SocketChannel client = null; serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(9000)); client = serverSocket.accept(); System.out.println(“Connection Set: ” + client.getRemoteAddress()); Path path = Paths.get(“C:/Test/temp1.txt”); FileChannel fileChannel = FileChannel.open(path, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE) ); ByteBuffer buffer = ByteBuffer.allocate(1024); while(client.read(buffer) > 0) { buffer.flip(); fileChannel.write(buffer); buffer.clear(); } fileChannel.close(); System.out.println(“File Received”); client.close(); } } Output Running the client will not print anything until server starts. Server: SocketChannelServer.java import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; public class SocketChannelServer { public static void main(String[] args) throws IOException { SocketChannel server = SocketChannel.open(); SocketAddress socketAddr = new InetSocketAddress(“localhost”, 9000); server.connect(socketAddr); Path path = Paths.get(“C:/Test/temp.txt”); FileChannel fileChannel = FileChannel.open(path); ByteBuffer buffer = ByteBuffer.allocate(1024); while(fileChannel.read(buffer) > 0) { buffer.flip(); server.write(buffer); buffer.clear(); } fileChannel.close(); System.out.println(“File Sent”); server.close(); } } Output Running the server will print the following. Connection Set: /127.0.0.1:49558 File Received Print Page Previous Next Advertisements ”;
Java NIO – Home
Java NIO Tutorial PDF Version Quick Guide Resources Job Search Discussion Java NIO is an open source JavaScript framework to build web applications in HTML and JavaScript. This tutorial looks at the various aspects of Java NIO framework which includes the basics of the framework, the setup of Angular and how to work with the various aspects of the framework. Other topics discussed in the tutorial are advanced chapters such as interfaces, nested components and services within Angular. Topics such as routing, modules, and arrays are also dealt with in this tutorial. Audience This tutorial is for those who are interested in learning the new version of the Angular framework. The first version of the framework has been there for quite some time and it is only off-late that Java NIO has become popular with the web development community. Prerequisites The user should be familiar with the basics of web development and JavaScript. Since the Angular framework is built on the JavaScript framework, it becomes easier for the user to understand Angular if they know JavaScript. Print Page Previous Next Advertisements ”;