运行jar文件时出现FileNotFoundException

时间:2014-03-05 20:35:03

标签: java filenotfoundexception

我有以下代码:

package test;


import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class SWTTest {

    public static void main(String[] args) {
        SWTTest test=new SWTTest(new Display());
        test.run();
    }


    private Shell shell;
    private Display display;


    public SWTTest(Display main_display) {
        display=main_display;

        shell=new Shell(display, SWT.DIALOG_TRIM);
        shell.setText("Test window");
        shell.setBackgroundImage(new Image(display,"./image/blue_screen.jpg"));
    }

    public void run() {

        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) 
                display.sleep();
        }
    }
}

这是编译和运行。问题是当我将其导出为jar文件时 只是为了确保我做得正确:
右键单击项目 - >导出...-> Runnable Jar文件 - >选择正确的启动配置,然后选择“完成”。
它创建了一个jar文件,但是当我从终端运行它时,我得到:

Exception in thread "main" org.eclipse.swt.SWTException: i/o error (java.io.FileNotFoundException: ./image/blue_screen.jpg (No such file or directory))
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.graphics.ImageLoader.load(Unknown Source)
    at org.eclipse.swt.graphics.ImageDataLoader.load(Unknown Source)
    at org.eclipse.swt.graphics.ImageData.<init>(Unknown Source)
    at org.eclipse.swt.graphics.Image.<init>(Unknown Source)
    at test.SWTTest.<init>(SWTTest.java:31)
    at test.SWTTest.main(SWTTest.java:13)
Caused by: java.io.FileNotFoundException: ./image/blue_screen.jpg (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at java.io.FileInputStream.<init>(FileInputStream.java:101)
    at org.eclipse.swt.internal.Compatibility.newFileInputStream(Unknown Source)
    ... 6 more

为什么它在Eclipse上运行,而不是作为jar文件运行? 为什么一下子找不到图像呢?

(我还会提到我在我的项目中添加了新的源文件夹,并将其命名为“image”,现在它位于“src”文件夹旁边 - 我想说的是“image”文件夹是我的Eclipse项目中的源文件夹) 那我在这里错过了什么?

1 个答案:

答案 0 :(得分:5)

当您的图像存储在jar中时,您需要将它们作为资源加载。沿着这些方向,你应该关闭流。

BufferedImage image = ImageIO.read(MyClass.class.getResourceAsStream("something.png"));

当你在Eclipse中运行时,你的目录中的图像是本地的,所以你可以使用通常的File对象看到它们,但是当它们在jar本身时就不能看到它们。