简体   繁体   English

Java获取具有引用名称的文件

[英]Java getting files with referenced name

I have a folder where images are stored for films with the same name as the film now when the user searches, the respective Image should show up for that film. 我有一个文件夹,用于存储与电影同名的电影的图像,现在当用户搜索时,应该为该电影显示相应的图像。

File ImageDisplay = new File("src/icons/random.png");  
BufferedImage originalImage = ImageIO.read(ImageDisplay);
ImageIcon icon = new ImageIcon(originalImage);

Now if i run this everything works fine and that image appear on every film. 现在,如果我运行该程序,一切正常,该图像出现在每部电影中。

But i want to do something like this: 但我想做这样的事情:

File ImageDisplay = new File("src/icons/"+MOVIE_TITLE+".png");  
BufferedImage originalImage = ImageIO.read(ImageDisplay);
ImageIcon icon = new ImageIcon(originalImage);

Where MOVIE_TITLE is the film name from the database. 其中MOVIE_TITLE是数据库中的电影名称。 But this gives me error which i cant seem to understand why. 但这给了我我似乎无法理解为什么的错误。 if i remove everything and just print it out by using: 如果我删除所有内容,然后使用以下命令将其打印出来:

System.out.println("src/icons/"+MOVIE_TITLE+".png");

The output in the console is correct for every movie where it prints out for example: The Godfather.png and so on. 控制台中的输出对于每部打印出来的电影都是正确的,例如:Godfather.png等。 What am i missing? 我想念什么?

I solved the problem. 我解决了问题。 The error was that all films didn't have images and when it couldnt find that image for a corresponding film it gave an error. 错误是所有电影都没有图像,并且当找不到对应电影的图像时出现错误。

I solved the problem by checking if the file exists first with this code: 我通过使用以下代码检查文件是否首先存在来解决了该问题:

 if(ImageDisplay.exists()) { 
             ImageDisplay = new File("src/icons/"+titleString+".png"); 
            } else {
                ImageDisplay = new File("src/icons/SsSs.png");
            }

And if the image doesn't exist replace it with another one. 如果图像不存在,请换一张。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM