简体   繁体   中英

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

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...

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

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