Java - 文件 writing/reading 适用于 Windows 但不适用于 Mac

Java - File writing/reading works on Windows but not Mac

我目前正在开发一个应用程序,我希望它能在 Windows 和其他操作系统上运行。

我 运行 遇到了一个问题,即从我程序中的文件夹调用的文件没有出现在 macOS 上,但出现在 Windows。

我的所有文件都以与此示例 GUI 代码相同的方式写入和读取:

public class GUI extends JFrame {
    private JLabel imageLabel;
    
    public GUI()  {
        this.setTitle("test");
        this.setSize(500,349);
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        imageLabel = new JLabel(new ImageIcon("assets/test.png"));
        
        this.getContentPane().setBackground(new Color(20,50,250));

        this.getContentPane().add(imageLabel);
        
        this.setSize(500, 350);
        
    }
}

在 Windows 上,GUI 程序如下所示:

在 MacOS 上,GUI 程序如下所示:

我想补充一点,这些是通过从 Eclipse IDE 导出的可运行 Jar 文件在操作系统上 运行。使用的版本是 JavaSE-1.8.

问题所在:

imageLabel = new JLabel(new ImageIcon("assets/test.png"));

我的解决方案:

imageLabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("test.png")));

解释:

我的初衷是以某种方式合并程序本身的资源,以便与 JAR 可执行文件一起工作。在我的测试中(我是制作可执行文件的新手),我发现除非我有一个单独的文件夹“assets”,否则用户也将使用 jar 文件下载该文件夹。虽然这个解决方案确实奏效了一点,但在某些机器上的某些读取和写入似乎有所不同。

为了使其正常工作,必须将“assets”文件夹或任何包含您的图像的文件夹添加到您的Java构建路径。

从这里开始,它适用于所有经过测试的机器; Windows 和 MacOS。