zoukankan      html  css  js  c++  java
  • JAVA NIO 新IO 分析 理解 深入 实例,如何利用JAVA NIO提升IO性能

    在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);
    	}
    
    }
    






















  • 相关阅读:
    面向对象程序设计课第五次作业
    面向对象程序设计课第三次作业
    MeasureSpec 解析
    JavaWeb学习总结(一)JavaWeb入门与Tomcat
    Redis GetTypedClient
    Visual Studio Entity Framework (EF) 生成SQL 代码 性能查询
    EF 连接MySQL 数据库  保存中文数据后乱码问题
    VS2015 +EF6 连接MYSQL数据库生成实体
    WebConfig 自定义节点configSections配置信息
    docker菜鸟入门
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3057395.html
Copyright © 2011-2022 走看看