简体   繁体   中英

Add text file and images to build in the Jar - Netbeans

I'm really facing too much of problem when building the Jar. The problem is within Netbeans it's work fine but if I try to run the .jar file from the /dest folder, it's not calling the additional text files and images. I tried various solutions but cannot really solve it. This is the directory that I stored the .java files. src/RX/example.java where RX is the package name. I inserted all the images and text files inside the same directory and called like this.

JButton btnStart = new JButton(new ImageIcon("src/RX/start1.png")); //Set Image for Button

Now reading from text file:

Reader reader = null; 
JTextArea jtaUser= new JTextArea(); 
try {
    reader = new FileReader(new File("src/RX/rxUser.txt"));
    jtaUser.read(reader, "");
} catch (Exception exp) {
} finally {
    try {
        reader.close();
    } catch (Exception exp) {
    }
}

As i said earlier, the problem is if I run from Netbeans everything's worked fine but the text files and images not included in the .jar file. Thus, when I open the .jar, the button seems empty and when reading the file it freezes.

I need an answer for the same coding I did above here. So, please tell me or show me how I can set the image and read the text file rather than giving links to other answers. I would really appreciate your answers for this question. Thank you.

When you read a file as a File object, the program will try and read from the local file system. If you are going to use a file as a resource, then you should read them as such.

You can get in InputStream from getClass().GetResourceAsStream() and then pass that InputStream to an InputStreamReader to use for the read() method. So in your case, you would use

InputStream is = getClass().getResourceAsStream("/RX/rxUsers.txt");
InputStreamReader reader = new InputStreamReader(is);
textArea.read(reader, ..);

The path I used is determined by the classpath. Since RX dir is a direct child of src , it will be in the root of the class path. To get to the root of the class path from the calling class (using getClass()), you need the extra / in the front of your path.

To read image, you can either use getResourceAsStream() which returns an InputStream , or use getResource() which return an URL. You can pass the URL to an ImageIcon(URL) or an ImageIO.read(URL) which return an Image object. Pick which one, based on your needs. Example:

URL url = getClass().getResource("/RX/start1.png"); // you will need to 
ImageIcon icon = new ImageIcon(url);                // handle exception

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