【问题标题】:Reading in Images to an ImageIcon Array List将图像读入 ImageIcon 数组列表
【发布时间】:2020-03-31 19:55:27
【问题描述】:

我正在尝试将图像从目录读取到数组列表,但我遇到了问题。我可能会出错,但似乎找不到解决方案。我发现了很多其他帖子,但他们只是在阅读一张指定的图片。

private ArrayList<ImageIcon> images = new ArrayList<>();
Scanner s;
        try {
            s = new Scanner(new File("/images"));
            while(s.hasNext()) {
                images.add(s.hasNext());
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

【问题讨论】:

  • 您的代码似乎正在读取文件的内容。您的问题提到从目录中读取。您是要从文本文件中读取文件名还是要列出文件夹的内容?
  • 您的new File("/images") 正在提供该文件夹。您需要带有图像文件名的完整路径。
  • 您没有阅读任何内容。 images.add(s.hasNext()); 返回是否有下一个 - 但它确实读取了

标签: java image io


【解决方案1】:

假设您正在尝试读取名称在您正在阅读的文本文件中的图像,这就是您将如何创建 ImageIcon 对象并将它们添加到列表中:

        s = new Scanner(new File("/images"));
        while(s.hasNext()) {
            String imageFileName = s.next()
            images.add(new ImageIcon(imageFileName));
        }

如果您尝试列出目录的内容,一种方法是使用File.listFiles 方法。

        File directory = new File("/images");
        for (File file : directory.listFiles()) {
            images.add(new ImageIcon(file.getPath()));
        }

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 2011-02-02
    • 2011-08-17
    • 1970-01-01
    • 2011-06-20
    • 2013-02-20
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    相关资源
    最近更新 更多