java - 加载jar文件中的资源目录

标签 java image jar directory photos

我找到了这段代码,我正在尝试将其调整到我的项目中。

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;

public class Album {

     static boolean contr = false;  
     static String path = "photos/";
     static int MAX;
     static String []imgName;
     static JLabel label = new JLabel();
     static JMenuBar mBar = new JMenuBar();
     static JMenu mn = new JMenu("open here ");
     static JMenuItem []menuItem;
     static JFrame fot = new JFrame();
     static JButton back = new JButton(" back ");


    public static void Album() {
        if (contr==true){
            fot.setVisible(true);
        }
        else{
            JFrame.setDefaultLookAndFeelDecorated(true); 
            File directory = new File(path);
            if (!directory.exists()) {
                System.err.println("The specified directory doesn't exist!!");
                err.err("fail.jpg");
            }
            try
            {
               UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            }  catch (Exception e) {
                // Do nothing
            }
            label.setHorizontalAlignment(SwingConstants.CENTER);
            label.setVerticalAlignment(SwingConstants.CENTER);
            mBar.updateUI();
            mn.updateUI();
            // Filter out the Images
            imgName = directory.list(new FilenameFilter() {
                String[] readFormat = ImageIO.getReaderFormatNames();

                @Override
                public boolean accept(File dir, String name) {
                    for (int i = 0; i < readFormat.length; i++) {
                        if (name.endsWith(readFormat[i])) {
                            return true;
                        }
                    }
                    return false;
                }
            });
            MAX = imgName.length;
            if (MAX == 0) {
                System.err.println("OOps , no images");
                System.exit(-1);
            }
            //Limit the maximunm entries to 10
            if (MAX > 19) {
                MAX = 19;
            }
            menuItem = new JMenuItem[MAX];
            for (int i = 0; i < menuItem.length; i++) {
                menuItem[i] = new JMenuItem(imgName[i].substring(0, imgName[i].lastIndexOf(".")), new ImageIcon(getImage(path + imgName[i]).getScaledInstance(32, 32, Image.SCALE_SMOOTH)));
                menuItem[i].updateUI();
                mn.add(menuItem[i]);
                menuItem[i].setActionCommand(imgName[i]);
                menuItem[i].addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        label.setIcon(new ImageIcon(getImage(path + ae.getActionCommand())));
                    }
                });
            }
            mBar.add(mn);
            fot.setJMenuBar(mBar);
            fot.add(new JScrollPane(label));
            fot.add(back, BorderLayout.AFTER_LAST_LINE);
            Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
            fot.setSize(scrDim.width-250 , scrDim.height-50);
            fot.setVisible(true);
            fot.setTitle("photo album");
            fot.setResizable(false);
            fot.setLocationRelativeTo(null);
            fot.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            back.addActionListener(new ActionListener() {   //back
                @Override
                public void actionPerformed(ActionEvent e) {
                    fot.setVisible(false);
                    contr=true;
                    menu.menu();
                }
            });
        }      
    }

    // Get the Image from the disk
    public static Image getImage(String fileName) {
        try {
            return ImageIO.read(new File(fileName));
        } catch (IOException ioe) {
            System.err.println("Error loading Image : " + fileName);
        }
        return null;
    }

}

我必须将所有内容导出到 .jar 文件中,从 eclipse 运行它可以正常工作,而一旦导出 .jar 文件就无法工作。问题是我找不到 photos/文件夹,它是资源的第二个文件夹,但也尝试根目录不起作用。相反,它可以读取 .jar 文件中的 eclipse,每个图像作为参数传递,以调用下一个在图像中显示错误消息的类:

err.err("fail.jpg");

项目文件夹的格式如下:

项目:

  • src(类)
  • 来源(图片)
  • 照片(照片)

所有路径名都是正确的,如“fail.jpg”。 我花了几周时间寻找解决方案,我需要知道如何直接从资源文件夹上传图像,以使它们直接在 .jar 文件中工作。非常感谢!

最佳答案

您应该考虑使用 getResourceAsStream("/fail.jpg") 方法来获取文件。一个例子看起来像

InputStream inputStream = Main.class.getResourceAsStream("/fail.jpg");

对于本示例,您的 jpg 文件应位于源文件夹中。

您可以使用 jar 文件中的任何类来代替 Main。

关于java - 加载jar文件中的资源目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33755305/

相关文章:

java - 缓存 AmazonS3 客户端以供以后使用是否安全?

java - 使用java 8以相反的顺序读取文件

java - 如何显示来自 HTTP Web 服务器的图像?

python - PNG 不会使用 image.getbbox() 自动裁剪

java - 带有 glassfish 的 netbeans 没有找到适合 mysql :jdbc 的驱动程序

java - jar文件的问题

java - HttpURLConnection 的性能问题

java - 如果输入与数组列表中的数字匹配,则无法获取方法 (getTest) 返回 true boolean 方法结果

jquery - 如何设置jquery创建的内容的图像宽度

java - 在 Java 中查找 eclipse/jdt 的 jar 依赖项