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》