我需要在我的代码中读取一个文件.它实际上驻留在这里:
C:\eclipseWorkspace\ProjectA\src\com\company\somePackage\MyFile.txt
Run Code Online (Sandbox Code Playgroud)
我把它放在一个源码包,这样,当我创建一个可运行jar文件(导出 - >运行的JAR文件),它被包含在瓶子里.最初我在项目根目录中使用它(并且还尝试了一个普通的子文件夹),但导出不包括在jar中.
如果在我的代码中我做:
File myFile = new File("com\\company\\somePackage\\MyFile.txt");
Run Code Online (Sandbox Code Playgroud)
jar文件正确定位文件,但本地运行(运行AS-> Java的主要应用)抛出了一个文件,未发现异常,因为它希望它是:
File myFile = new File("src\\com\\company\\somePackage\\MyFile.txt");
Run Code Online (Sandbox Code Playgroud)
但这在我的jar文件中失败了.所以我的问题是,如何让这个概念在本地和我的jar文件中运行?
我有以下代码:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是编译和运行.问题是当我将其导出为jar文件时.
只是为了确保我做得正确:
右键单击项目 - > export ...-> Runnable Jar文件 - >选择正确的启动配置,然后选择'完成'.
它创建了一个jar文件,但是当我从终端运行它时,我得到:
Exception in thread "main" org.eclipse.swt.SWTException: i/o error (java.io.FileNotFoundException: …Run Code Online (Sandbox Code Playgroud)