简体   繁体   中英

Uncompiled jar works but compiled doesn't work

So in Eclipse this code works:

String file_path = "accounts.accs";
File file = new File("src/puffinlump/folder_lock/"+file_path);

But when I compile it into a JAR I get this error:

Error reading file: java.io.FileNotFoundException: lock\src\puffinlump\folder_lock\accounts.accs (The system cannot find the path specified)

Why is it not working and how can I fix it?

As Obicere said, the working directory is the project directory. You try to access something in the src folder, which probably doesn't exist wherever you exported your JAR. You should create a folder named folder_lock in your project directory with accounts.accs in it, then get your file with:

File file = new File("folder_lock" + File.separator + "accounts.accs");

If you need it in your JAR (which it's being exported to, given that it's in the src folder) then retrieve an InputStream from it like this:

InputStream stream = getClass().getClassLoader().getResourceAsStream("puffinlump/folder_lock/accounts.accs");

If your method is static, use

InputStream stream = MyClass.class.getClassLoader().getResourceAsStream("puffinlump/folder_lock/accounts.accs");

instead, substituting your class name over MyClass .

If you need an URL, you can retrieve one with getResource instead of getResourceAsStream .

Note that your code must be compiled to run - Eclipse compiles it by default every time you save.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM