您的位置:首页 > 编程语言 > Java开发

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

2013-11-19 00:00 113 查看
public class FileTest {

@Test

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》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jdk7 nio