Java NIO – File ”; Previous Next 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(); } } } Output Created a file at : D:datafile.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<String> 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<String> 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<String> 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? Print Page Previous Next Advertisements ”;
Category: java Nio
Java NIO – ServerSocket Channel ”; Previous Next Java NIO server socket channel is again a selectable type channel used for stream oriented data flow connecting sockets.Server Socket channel can be created by invoking its static open() method,providing any pre-existing socket is not already present.Server Socket channel is created by invoking open method but not yet bound.In order to bound socket channel bind() method is to be called. One point to be mentioned here is if channel is not bound and any I/O operation is tried to be attempted then NotYetBoundException is thrown by this channel.So one must be ensure that channel is bounded before performing any IO operation. Incoming connections for the server socket channel are listen by calling the ServerSocketChannel.accept() method. When the accept() method returns, it returns a SocketChannel with an incoming connection. Thus, the accept() method blocks until an incoming connection arrives.If the channel is in non-blocking mode then accept method will immediately return null if there are no pending connections. Otherwise it will block indefinitely until a new connection is available or an I/O error occurs. The new channel”s socket is initially unbound; it must be bound to a specific address via one of its socket”s bind methods before connections can be accepted.Also the new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object. Like socket channel server socket channel could read data using read() method.Firstly the buffer is allocated. The data read from a ServerSocketChannel is stored into the buffer.Secondly we call the ServerSocketChannel.read() method and it reads the data from a ServerSocketChannel into a buffer. The integer value of the read() method returns how many bytes were written into the buffer Similarly data could be written to server socket channel using write() method using buffer as a parameter.Commonly uses write method in a while loop as need to repeat the write() method until the Buffer has no further bytes available to write. 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. accept() − This method is used to accepts a connection made to this channel”s socket. 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() − Open method is used open a socket channel for no specified address.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting server 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. setOption(SocketOption<T> name, T value) − This method sets the value of a socket option. socket() − This method retrieves a server socket associated with this channel. validOps() − This method returns an operation set identifying this channel”s supported operations.Server-socket channels only support the accepting of new connections, so this method returns SelectionKey.OP_ACCEPT. Example The following example shows the how to send data from Java NIO ServerSocketChannel. 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 – Quick Guide
Java NIO – Quick Guide ”; Previous Next Java NIO – Overview Java.nio package was introduced in java 1.4. In contrast of java I/O in java NIO the buffer and channel oriented data flow for I/O operations is introduced which in result provide faster execution and better performance. Also NIO API offer selectors which introduces the functionality of listen to multiple channels for IO events in asynchronous or non blocking way.In NIO the most time-consuming I/O activities including filling and draining of buffers to the operating system which increases in speed. The central abstractions of the NIO APIs are following − Buffers,which are containers for data,charsets and their associated decoders and encoders,which translate between bytes and Unicode characters. Channels of various types,which represent connections to entities capable of performing I/O operations Selectors and selection keys, which together with selectable channels define a multiplexed, non-blocking I/O facility. Java NIO – Environment Setup 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/. Java NIO vs IO As we know that java NIO is introduced for advancement of conventional java IO API.The main enhancements which make NIO more efficient than IO are channel data flow model used in NIO and use of operating system for conventional IO tasks. The difference between Java NIO and Java IO can be explained as following − As mentioned in previous post in NIO buffer and channel oriented data flow for I/O operations which provide faster execution and better performance as compare to IO.Also NIO uses operating system for conventional I/O tasks which again makes it more efficient. Other aspect of difference between NIO and IO is this IO uses stream line data flow i.e one more byte at a time and relies on converting data objects into bytes and vice-e-versa while NIO deals with the data blocks which are chunks of bytes. In java IO stream objects are unidirectional while in NIO channels are bidirectional meaning a channel can be used for both reading and writing data. The streamline data flow in IO does not allow move forth and back in the data.If case need to move forth and back in the data read from a stream need to cache it in a buffer first.While in case of NIO we uses buffer oriented which allows to access data back and forth without need of caching. NIO API also supports multi threading so that data can be read and written asynchronously in such as a way that while performing IO operations current thread is not blocked.This again make it more efficient than conventional java IO API. Concept of multi threading is introduced with the introduction of Selectors in java NIO which allow to listen to multiple channels for IO events in asynchronous or non blocking way. Multi threading in NIO make it Non blocking which means that thread is requested to read or write only when data is available otherwise thread can be used in other task for mean time.But this is not possible in case of conventional java IO as no multi threading is supported in it which make it as Blocking. NIO allows to manage multiple channels using only a single thread,but the cost is that parsing the data might be somewhat more complicated than when reading data from a blocking stream in case of java IO.So in case fewer connections with very high bandwidth are required with sending a lot of data at a time,than in this case java IO API might be the best fit. Java NIO – Channels 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
Java NIO – Discussion
Discuss Java NIO ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Java NIO – CharSet
Java NIO – CharSet ”; Previous Next 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. 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. Print Page Previous Next Advertisements ”;
Java NIO – Selector
Java NIO – Selector ”; Previous Next As we know that Java NIO supports multiple transaction from and to channels and buffer.So in order to examine one or more NIO Channel”s, and determine which channels are ready for data transaction i.e reading or writing Java NIO provide Selector. With Selector we can make a thread to know that which channel is ready for data writing and reading and could deal that particular channel. We can get selector instance by calling its static method open().After open selector we have to register a non blocking mode channel with it which returns a instance of SelectionKey. SelectionKey is basically a collection of operations that can be performed with channel or we can say that we could know the state of channel with the help of selection key. The major operations or state of channel represented by selection key are − SelectionKey.OP_CONNECT − Channel which is ready to connect to server. SelectionKey.OP_ACCEPT − Channel which is ready to accept incoming connections. SelectionKey.OP_READ − Channel which is ready to data read. SelectionKey.OP_WRITE − Channel which is ready to data write. Selection key obtained after registration has some important methods as mentioned below − attach() − This method is used to attach an object with the key.The main purpose of attaching an object to a channel is to recognizing the same channel. attachment() − This method is used to retain the attached object from the channel. channel() − This method is used to get the channel for which the particular key is created. selector() − This method is used to get the selector for which the particular key is created. isValid() − This method returns weather the key is valid or not. isReadable() − This method states that weather key”s channel is ready for read or not. isWritable() − This method states that weather key”s channel is ready for write or not. isAcceptable() − This method states that weather key”s channel is ready for accepting incoming connection or not. isConnectable() − This method tests whether this key”s channel has either finished, or failed to finish, its socket-connection operation. isAcceptable() − This method tests whether this key”s channel is ready to accept a new socket connection. interestOps() − This method retrieves this key”s interest set. readyOps() − This method retrieves the ready set which is the set of operations the channel is ready for. We can select a channel from selector by calling its static method select().Select method of selector is overloaded as − select() − This method blocks the current thread until at least one channel is ready for the events it is registered for. select(long timeout) − This method does the same as select() except it blocks the thread for a maximum of timeout milliseconds (the parameter). selectNow() − This method doesn”t block at all.It returns immediately with whatever channels are ready. Also in order to leave a blocked thread which call out select method,wakeup() method can be called from selector instance after which the thread waiting inside select() will then return immediately. In last we can close the selector by calling close() method which also invalidates all SelectionKey instances registered with this Selector along with closing the selector. Example import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class SelectorDemo { public static void main(String[] args) throws IOException { String demo_text = “This is a demo String”; Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.bind(new InetSocketAddress(“localhost”, 5454)); serverSocket.configureBlocking(false); serverSocket.register(selector, SelectionKey.OP_ACCEPT); ByteBuffer buffer = ByteBuffer.allocate(256); while (true) { selector.select(); Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> iter = selectedKeys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); int interestOps = key.interestOps(); System.out.println(interestOps); if (key.isAcceptable()) { SocketChannel client = serverSocket.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ); } if (key.isReadable()) { SocketChannel client = (SocketChannel) key.channel(); client.read(buffer); if (new String(buffer.array()).trim().equals(demo_text)) { client.close(); System.out.println(“Not accepting client messages anymore”); } buffer.flip(); client.write(buffer); buffer.clear(); } iter.remove(); } } } } Print Page Previous Next Advertisements ”;
Java NIO – Buffer
Java NIO – Buffer ”; Previous Next Buffers in Java NIO can be treated as a simple object which act as a fixed sized container of data chunks that can be used to write data to channel or read data from channel so that buffers act as endpoints to the channels. It provide set of methods that make more convenient to deal with memory block in order to read and write data to and from channels. Buffers makes NIO package more efficient and faster as compared to classic IO as in case of IO data is deal in the form of streams which do not support asynchronous and concurrent flow of data.Also IO does not allow data execution in chunk or group of bytes. Primary parameters that defines Java NIO buffer could be defined as − Capacity − Maximum Amount of data/byte that can be stored in the Buffer.Capacity of a buffer can not be altered.Once the buffer is full it should be cleared before writing to it. Limit − Limit has meaning as per the mode of Buffer i.e. in write mode of Buffer Limit is equal to the capacity which means that maximum data that could be write in buffer.While in read mode of buffer Limit means the limit of how much data can be read from the Buffer. Position − Points to the current location of cursor in buffer.Initially setted as 0 at the time of creation of buffer or in other words it is the index of the next element to be read or written which get updated automatically by get() and put() methods. Mark − Mark a bookmark of the position in a buffer.When mark() method is called the current position is recorded and when reset() is called the marked position is restored. Buffer Type Java NIO buffers can be classified in following variants on the basis of data types the buffer deals with − ByteBuffer MappedByteBuffer CharBuffer DoubleBuffer FloatBuffer IntBuffer LongBuffer ShortBuffer Important methods of Buffer As mentioned already that Buffer act as memory object which provide set of methods that make more convenient to deal with memory block.Following are the important methods of Buffer − allocate(int capacity) − This method is use to allocate a new buffer with capacity as parameter.Allocate method throws IllegalArgumentException in case the passed capacity is a negative integer. read() and put() − read method of channel is used to write data from channel to buffer while put is a method of buffer which is used to write data in buffer. flip() − The flip method switches the mode of Buffer from writing to reading mode.It also sets the position back to 0, and sets the limit to where position was at time of writing. write() and get() − write method of channel is used to write data from buffer to channel while get is a method of buffer which is used to read data from buffer. rewind() − rewind method is used when reread is required as it sets the position back to zero and do not alter the value of limit. clear() and compact() − clear and compact both methods are used to make buffer from read to write mode.clear() method makes the position to zero and limit equals to capacity,in this method the data in the buffer is not cleared only the markers get re initialized. On other hand compact() method is use when there remained some un-read data and still we use write mode of buffer in this case compact method copies all unread data to the beginning of the buffer and sets position to right after the last unread element.The limit property is still set to capacity. mark() and reset() − As name suggest mark method is used to mark any particular position in a buffer while reset make position back to marked position. Example The following example shows the implementation of above defined methods. import java.nio.ByteBuffer; import java.nio.CharBuffer; public class BufferDemo { public static void main (String [] args) { //allocate a character type buffer. CharBuffer buffer = CharBuffer.allocate(10); String text = “bufferDemo”; System.out.println(“Input text: ” + text); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); //put character in buffer. buffer.put(c); } int buffPos = buffer.position(); System.out.println(“Position after data is written into buffer: ” + buffPos); buffer.flip(); System.out.println(“Reading buffer contents:”); while (buffer.hasRemaining()) { System.out.println(buffer.get()); } //set the position of buffer to 5. buffer.position(5); //sets this buffer”s mark at its position buffer.mark(); //try to change the position buffer.position(6); //calling reset method to restore to the position we marked. //reset() raise InvalidMarkException if either the new position is less //than the position marked or merk has not been setted. buffer.reset(); System.out.println(“Restored buffer position : ” + buffer.position()); } } Output Input text: bufferDemo Position after data is written into buffer: 10 Reading buffer contents: b u f f e r D e m o Restored buffer position : 5 Print Page Previous Next Advertisements ”;
Java NIO – DataGram Channel
Java NIO – Datagram Channel ”; Previous Next Java NIO Datagram is used as channel which can send and receive UDP packets over a connection less protocol.By default datagram channel is blocking while it can be use in non blocking mode.In order to make it non-blocking we can use the configureBlocking(false) method.DataGram channel can be open by calling its one of the static method named as open() which can also take IP address as parameter so that it can be used for multi casting. Datagram channel alike of FileChannel do not connected by default in order to make it connected we have to explicitly call its connect() method.However datagram channel need not be connected in order for the send and receive methods to be used while it must be connected in order to use the read and write methods, since those methods do not accept or return socket addresses. We can check the connection status of datagram channel by calling its isConnected() method.Once connected, a datagram channel remains connected until it is disconnected or closed.Datagram channels are thread safe and supports multi-threading and concurrency simultaneously. Important methods of datagram channel bind(SocketAddress local) − This method is used to bind the datagram channel”s socket 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. disconnect() − This method is used to disconnect the socket to the remote address. 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 datagram channel i.e whether it is connected or not. open() and open(ProtocolFamily family) − Open method is used open a datagram channel for single address while parametrized open method open channel for multiple addresses represented as protocol family. read(ByteBuffer dst) − This method is used to read data from the given buffer through datagram channel. receive(ByteBuffer dst) − This method is used to receive datagram via this channel. send(ByteBuffer src, SocketAddress target) − This method is used to send datagram via this channel. Example The following example shows the how to send data from Java NIO DataGramChannel. Server: DatagramChannelServer.java import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; public class DatagramChannelServer { public static void main(String[] args) throws IOException { DatagramChannel server = DatagramChannel.open(); InetSocketAddress iAdd = new InetSocketAddress(“localhost”, 8989); server.bind(iAdd); System.out.println(“Server Started: ” + iAdd); ByteBuffer buffer = ByteBuffer.allocate(1024); //receive buffer from client. SocketAddress remoteAdd = server.receive(buffer); //change mode of buffer buffer.flip(); int limits = buffer.limit(); byte bytes[] = new byte[limits]; buffer.get(bytes, 0, limits); String msg = new String(bytes); System.out.println(“Client at ” + remoteAdd + ” sent: ” + msg); server.send(buffer,remoteAdd); server.close(); } } Output Server Started: localhost/127.0.0.1:8989 Client: DatagramChannelClient.java import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; public class DatagramChannelClient { public static void main(String[] args) throws IOException { DatagramChannel client = null; client = DatagramChannel.open(); client.bind(null); String msg = “Hello World!”; ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes()); InetSocketAddress serverAddress = new InetSocketAddress(“localhost”, 8989); client.send(buffer, serverAddress); buffer.clear(); client.receive(buffer); buffer.flip(); client.close(); } } Output Running the client will print the following output on server. Server Started: localhost/127.0.0.1:8989 Client at /127.0.0.1:64857 sent: Hello World! Print Page Previous Next Advertisements ”;
Java NIO vs JAVA IO
Java NIO vs IO ”; Previous Next As we know that java NIO is introduced for advancement of conventional java IO API.The main enhancements which make NIO more efficient than IO are channel data flow model used in NIO and use of operating system for conventional IO tasks. The difference between Java NIO and Java IO can be explained as following − As mentioned in previous post in NIO buffer and channel oriented data flow for I/O operations which provide faster execution and better performance as compare to IO.Also NIO uses operating system for conventional I/O tasks which again makes it more efficient. Other aspect of difference between NIO and IO is this IO uses stream line data flow i.e one more byte at a time and relies on converting data objects into bytes and vice-e-versa while NIO deals with the data blocks which are chunks of bytes. In java IO stream objects are unidirectional while in NIO channels are bidirectional meaning a channel can be used for both reading and writing data. The streamline data flow in IO does not allow move forth and back in the data.If case need to move forth and back in the data read from a stream need to cache it in a buffer first.While in case of NIO we uses buffer oriented which allows to access data back and forth without need of caching. NIO API also supports multi threading so that data can be read and written asynchronously in such as a way that while performing IO operations current thread is not blocked.This again make it more efficient than conventional java IO API. Concept of multi threading is introduced with the introduction of Selectors in java NIO which allow to listen to multiple channels for IO events in asynchronous or non blocking way. Multi threading in NIO make it Non blocking which means that thread is requested to read or write only when data is available otherwise thread can be used in other task for mean time.But this is not possible in case of conventional java IO as no multi threading is supported in it which make it as Blocking. NIO allows to manage multiple channels using only a single thread,but the cost is that parsing the data might be somewhat more complicated than when reading data from a blocking stream in case of java IO.So in case fewer connections with very high bandwidth are required with sending a lot of data at a time,than in this case java IO API might be the best fit. Print Page Previous Next Advertisements ”;
Java NIO – Useful Resources
Java NIO – Useful Resources ”; Previous Next The following resources contain additional information on Java NIO. Please use them to get more in-depth knowledge on this topic. Useful Links on Java NIO The JavaTM Tutorials − The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. JavaTM 2 SDK, Standard Edition − Official site for JavaTM 2 SDK, Standard Edition Free Java Download − Download Java for your desktop computer now! Sun Developer Network − Sun Microsystem”s official website listing down all the API documentation, latest Java Technologies, Books and other resource. Useful Books on Java NIO To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;