我正在加载大量将在我的应用程序中使用的图标。我计划在服务器启动时从 jar 中加载所有这些。然而,由于数百张图像加起来刚刚超过 9MB,执行此任务仍然需要 30 秒多的时间。我现在正在一个单独的线程中执行此操作,但这让我想知道我是否在代码中执行了低效的操作。我从 SO 借用了代码来将信息加载到我的结构中。我将代码放入测试类并对其进行分析。 99% 的配置文件都在 ImageIO.read(..) 方法上。所以这绝对是瓶颈。下面是应该提供有关我如何使用 ImageIO 的图片的测试类。
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
为假:
您可以尝试使用ImageIO.setUseCache(false)
为了使用基于内存的缓存而不是基于磁盘的缓存(因为它是默认的)。
参考:https://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html#setUseCache(boolean) https://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html#setUseCache(boolean)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)