我正在加载将在我的应用程序中使用的图标。我计划在服务器启动时从jar中加载它们。但是,有数百张图片加起来只有9MB,但它仍然需要30多秒来完成这项任务。我现在正在一个单独的线程中执行它,但它让我怀疑在代码中是否无效地做了某些事情。我借用了SO的代码将信息加载到我的结构中。我将代码放入测试类并对其进行分析。该配置文件的99%位于ImageIO.read(..)方法中。所以这绝对是瓶颈。下面是应该提供关于我如何使用ImageIO的图片的测试类。ImageIO.read(...) - 速度很慢,有没有更好的方法?
public class IconTest {
/**
* @param args the command line arguments
* @throws java.net.URISyntaxException
* @throws java.io.IOException
*/
public static void main(String[] args) throws URISyntaxException, IOException {
URI uri = IconTest.class.getResource("Icons").toURI();
Path myPath;
if (uri.getScheme().equals("jar")) {
FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap());
myPath = fileSystem.getPath("Icons/");
} else {
myPath = Paths.get(uri);
}
IconFolder root = new IconFolder(myPath.toFile().getName());
IconFolder parentFolder = root;
HIcon currentIcon = null;
IconFolder folder = null;
HashMap<String,IconFolder> folders = new HashMap<>();
folders.put(parentFolder.getName(), parentFolder);
Stream<Path> walk = Files.walk(myPath, 5);
Iterator<Path> it = walk.iterator();it.next();
while(it.hasNext()){
Path path = it.next();
if(path.toFile().isDirectory()){
folder = new IconFolder(path.toFile().getName());
folders.put(folder.getName(), folder);
String parentName = path.getParent().toFile().getName();
parentFolder = folders.get(parentName);
parentFolder.addSubFolder(folder);
currentIcon =null;
System.out.println("Directory: " + path);
}else{
URL url = path.toUri().toURL();
ImageIcon icon = new ImageIcon(ImageIO.read(url));
//Image image = Toolkit.getDefaultToolkit().getImage(url);
//ImageIcon icon = new ImageIcon(image);
String[] iconName;
iconName = path.getFileName().toString().replaceAll("_000000", "").replaceAll(".png","").split("_",2);
String imageName = iconName[0];
String imageSize = iconName[1];
if(currentIcon==null||!currentIcon.getName().equals(imageName)){
currentIcon = new HIcon(imageName);
folder.addIcon(currentIcon);
currentIcon.setIcon(icon, imageSize);
}else{
currentIcon.setIcon(icon, imageSize);
}
//System.out.println("Image: " + imageName+"-->"+imageSize);
}
}
System.out.println("");
}
}
任何指针都会有帮助。我看了很多SO帖子,我认为这些帖子都指出了同样的事情。我正在使用带有SSD的MacBook Air,所以我认为这将会闪电般快速。
我加了下面的轮廓结果的截图:
这是设置setUseCache
假后的轮廓:
我会质疑整个策略。我会加载他们,因为你需要他们。分散痛苦。 – EJP
将图标放在一张图像中并稍后将它们剪下可能会大大加快。从罐子里读取的100个图像可能是低效的。 – pvg
@pvg - 请参阅我对以下答案的评论。将它们放入zip文件,将1个文件加载到内存中然后执行我的步行和在内存中读取? – Mark