Channels are used in concert with the buffer in NIO. A channel is a bidirectional channel that is readable and writable. It is a bit similar to stream, but stream is unidirectional, the application does not directly perform read/write operations on the channel, but must use the buffer. For example, when reading a channel, you must first read the data into the corresponding buffer and then read it in the buffer.
An example of using filechannel
Package NiO; import Java. io. *; import Java. NIO. bytebuffer; import Java. NIO. channels. filechannel; public class readdemo {public static void main (string [] ARGs) throws exception {long begin = system. currenttimemillis (); file = new file ("a.txt"); system. out. println (file. length (); file file2 = new file ("demo.txt"); fileinputstream fin = new fileinputstream (File); // read data from the file channel, bufferfilechannel fc = fin must be used. getchannel (); bytebuffer BB = bytebuffer. allocate (1, 430528); FC. read (bb); FC. close (); bb. flip (); fileoutputstream Fos = new fileoutputstream (file2); filechannel FC2 = FOS. getchannel (); fc2.write (bb); long end = system. currenttimemillis (); system. out. println (end-begin );}}
An example of using bufferedreader and bufferedwriter
package nio;import java.io.*;public class BufferReadDemo {/** * @param args * @throws Exception */public static void main(String[] args) throws Exception {// TODO Auto-generated method stublong begin = System.currentTimeMillis();File file = new File("a.txt");System.out.println(file.length());File file2 = new File("demo.txt");BufferedReader br = new BufferedReader(new FileReader(file));BufferedWriter bw = new BufferedWriter(new FileWriter(file2));//StringBuffer sb = new StringBuffer("");String str = "";while((str=br.readLine())!=null) {//sb.append(str);//sb.append("\n");bw.write(str);bw.write("\n");}//bw.write(sb.toString().getBytes());long end = System.currentTimeMillis();System.out.println(end-begin);}}