瘋狂

          STANDING ON THE SHOULDERS OF GIANTS
          posts - 481, comments - 486, trackbacks - 0, articles - 1
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          nio和io讀寫文件

          Posted on 2010-02-05 15:49 瘋狂 閱讀(813) 評論(0)  編輯  收藏 所屬分類: java


          nio:
          public static void testNio() throws IOException{
           long start = System.currentTimeMillis();
           FileInputStream in = new FileInputStream(new File("C:\\y.war"));
           FileOutputStream out = new FileOutputStream(new File("C:\\copy1.war"));
           FileChannel outc = out.getChannel();
           FileChannel inc = in.getChannel();
           ByteBuffer inb = ByteBuffer.allocate(1024*1024);//1m
           int i = 0;
           while(true){
            i++;
            System.out.println("第"+i+"次傳輸...");
            if(inb.position()>0){
             System.out.println("clear...");
             inb.clear();
            }
            if(inc.read(inb)==-1)break;
            inb.flip();
            outc.write(inb);
           }
           inc.close();
           outc.close();
           System.out.println("耗時:"+(System.currentTimeMillis()-start)+"毫秒");
          }

          io:
          public static void testIo() throws IOException{
           long start = System.currentTimeMillis();
           FileInputStream in = new FileInputStream(new File("C:\\y.war"));
           FileOutputStream out = new FileOutputStream(new File("C:\\copy2.war"));
           
           BufferedInputStream inc = new BufferedInputStream(in);
           BufferedOutputStream outc = new BufferedOutputStream(out);
           byte[] inb = new byte[1024*1024];//1m
           int i = 0;
           int l=-1;
           while(true){
            i++;
            System.out.println("第"+i+"次傳輸...");
            if((l=inc.read(inb))==-1)break;
            outc.write(inb,0,l);
           }
           inc.close();
           outc.flush();
           outc.close();
           System.out.println("耗時:"+(System.currentTimeMillis()-start)+"毫秒");
          }
          }
          同樣的16.4 MB的文件100次讀寫測試平均耗時:nio耗時:80毫秒 io耗時:105毫秒
          主站蜘蛛池模板: 泸定县| 台南县| 女性| 梓潼县| 南平市| 琼结县| 庆安县| 双峰县| 鄂托克前旗| 富裕县| 阳原县| 长治县| 枣庄市| 无为县| 奉节县| 财经| 历史| 阿拉尔市| 山东| 湘潭市| 佛冈县| 寿光市| 冀州市| 邻水| 桐庐县| 富蕴县| 福建省| 温泉县| 郴州市| 吉林省| 定西市| 栖霞市| 旺苍县| 克拉玛依市| 信宜市| 临沧市| 大庆市| 兴化市| 如皋市| 怀仁县| 天台县|