ImageIO.write写文件的速度如何?

huanghuang 发布于 2011/07/25 12:59
阅读 4K+
收藏 0
java写文件用ImageIO.write 和FileOutputStream+BufferedOutputStream,哪个写文件速度快?
加载中
0
红薯
红薯
有缓冲的更快一点
0
huanghuang
huanghuang

继续针对上面的问题,抛出一段代码。

问题讨论的来源:有6万多个小于6k的小文件需要写到硬盘上,我采用了多线程,最大线程数200,并行数设置了50,大家可以测试运行一下,我的参数设置的是否合理,最终目的是测试一下用多线程写6万个小于6k文件用多长时间。

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.Serializable;
import java.net.URL;
import java.sql.Timestamp;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
 * 写几万个小于6k的文件工作类
 * @author Admin
 *
 */
public class MyWork {
 public static void main(String[] args) {
  Timestamp startTime = new Timestamp(System.currentTimeMillis());
  MyWork my =new MyWork();
  my.doIt();
  Timestamp entTime1 = new Timestamp(System.currentTimeMillis());
  long time_b = startTime.getTime();
  long time_a = entTime1.getTime();
  long totalTime1 = time_a - time_b;
  long totalsecond1 = totalTime1 / 1000;
  System.out.println("totalsecond1=" + totalsecond1);
 }
 public void doIt( ) { 
  ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 200, 3,
     TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50),
     new ThreadPoolExecutor.CallerRunsPolicy());
  //我机器运行用时记录的结果
   //3000个文件用时: 26s          
   //60000个文件用时: 521s              
      
  int maxFileCount=60000; //待写文件个数
  for (int i=0;i<maxFileCount;i++) {  
 
           String task = ""+ i;

           threadPool.execute(new MyThread(task));
   }
 }
 /**
  * 线程类
  * @author Admin
  *
  */
 private  class MyThread implements Runnable,Serializable {

  /**
   *
   */
  private static final long serialVersionUID = 1L;
  private Object threadPoolTaskData;


  private MyThread( Object task) {
         this.threadPoolTaskData = task;
  }
  public Object getTask(){
   return this.threadPoolTaskData;
   }

  @Override
  public void run() {
   System.out.println("start .."+threadPoolTaskData);

   try {

    ImageIcon imageIcon = new ImageIcon("d://s.png");//读本机文件    
    BufferedImage bufferedImage = new BufferedImage(256, 256, BufferedImage.TYPE_4BYTE_ABGR);  
    
     Graphics   gc   =   bufferedImage.createGraphics();     
              gc.drawImage(imageIcon.getImage(),0,0,imageIcon.getImageObserver()); 
    
    ImageIO.write(bufferedImage, "png", new File("d://bbb//a007"+threadPoolTaskData+".png"));
       gc.dispose();
       gc=null;
   } catch (Exception e) {
    System.out.println("yichang"+ e.getMessage()); 
    
   }
   threadPoolTaskData =null;
  }
  } 
}

返回顶部
顶部