jdk7 NIO的读取目录下所有图片(文件)

public class FileTest {
public void test() throws IOException{
long start = System.currentTimeMillis();
String path="G:\\图片";
Path p = Paths.get(path);
              //放文件对应的Path对象,可以通过toFile方法得到File对象 
              //这里没有语法错误,是jdk7的新特性 
List<Path> result = new ArrayList<>();
               //筛选.jpg,.png,.gif格式图片 
      try (DirectoryStream<Path> stream = Files.newDirectoryStream(p, "*.{jpg,png,gif}")) {
          for (Path entry: stream) {
              result.add(entry);
          }
                //同样是jdk7的新特性,避免庞大的catch块 
      } catch (DirectoryIteratorException | IOException e) {
          e.printStackTrace();
      }
    //制定hashmap的容量,防止rehashing的巨大开销
    Map<String,byte[]> map = Maps.newHashMapWithExpectedSize(200);
    BufferedInputStream b = null;
        ByteArrayOutputStream out = null;
        BufferedOutputStream o = null;
        String fileName = null;
        
    for(Path currentPath:result ){
      if(Files.isReadable(currentPath)){
       try{
       b = new BufferedInputStream(Files.newInputStream(currentPath, StandardOpenOption.READ));
       out = new ByteArrayOutputStream();
       o = new BufferedOutputStream(out);
       fileName = currentPath.getFileName().toString();
       System.out.println("============文件名=================="+fileName);
       byte[] transition = new byte[1024];
       int i = 0;
       while((i=b.read(transition))!=-1){
       o.write(transition);
       }
       map.put(fileName, out.toByteArray());
       }finally{
       if(b!=null){
       b.close();
       }
       if(o!=null){
        o.close();
       }
       }
      }else{
       throw new FileNotFoundException("读取图片出错");
      }
    }
    long end = System.currentTimeMillis();
             //265个图片858毫秒,由于上边我的hashmap定义的容量是200,所以中间经过了rehashing,因此时间其实可以更短
    System.out.println("时间差================"+(end-start));

}




u can do anything u set your mind to man!————Eminem ,《8 miles》

转载于:https://my.oschina.net/stillotherguy/blog/177341

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值