在NIO中和BUFFER配合使用的有CHANNEL,channel是一个双向通道,既可读也可写,有点类似stream,但stream是单向的,应用程序不直接对channel进行读写操作,而必须通过buffer来进行。比如,在读一个channel的时候,需要先将数据读入到相对应的buffer,然后在buffer中进行读取。
一个使用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 file = new File("a.txt"); System.out.println(file.length()); File file2 = new File("demo.txt"); FileInputStream fin = new FileInputStream(file); //要从文件channel中读取数据,必须使用buffer FileChannel fc = fin.getChannel(); ByteBuffer bb = ByteBuffer.allocate(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); } }
一个使用bufferedreader,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 stub long 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); } }