sakura
sakura

Reputation: 309

Java code cannot find resource file after build and clean in Netbeans IDE?

I really need your help to solve my own problem. Now, I'm dealing with small code app. In that project folder contain some resource files (*.xlsx, *.png,...). I placed them in current folder with code file. I just wonder that when I run my code in netbean ide, it just worked find.

After I build code project, I get a jar file in "dist" directory. I run it. It open normally since app used JFrame as user interface. However, when I execute some function of that app, it showed me the error log. Here is the error message:

java.io.FileNotFoundException: 
src\sample.xlsx (The system cannot find the path specified)

What's the matter out there?

Here is some pieces of my code:

copyFile(new File("src\\sample.xlsx"),
new File(txtout.getText()+"\\sample.xlsx"));

Node: copyFile function is used for copy file from source to dest.

Here is my project folder structure in Netbean IDE:

  1. Project Name
    • Source Pakage(src)
      • myClass.java, sample.xlsx, etc

Upvotes: 1

Views: 3921

Answers (2)

SparkOn
SparkOn

Reputation: 8946

Well you can create a folder named resources under the src folder put your resources in it and use them in your code by using getResourceAsStream() and getResource() methods that can access the embedded resources.Clean and Build will compile the code and embed the contents of the resources folder into the application’s .jar file. Ways of Accessing resources :

    String pathToImage = "resources/images/filling.png";
    InputStream stream= ClassName.class.getResourceAsStream(pathToImage );

   String pathToImage = "resources/images/filling.png";
   InputStream stream= ClassName.class.getResource(pathToImage );

please refer the link information

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347204

First, never reference src directly, the directory will not exist once the program is built. Second, you can not access resources which have been embedded within in the application context via a File reference, they simply no longer exist on the file system.

Instead, you need to use Class#getResource or Class#getResourceAsStream

URL url = getClass().getResource("/sample.xlsx");
InputStream is = getClass().getResourceAsStream("/sample.xlsx");
// Don't forget to manage your streams appropriately...

Upvotes: 3

Related Questions