Java code to load resource image or file located inside jar example

In this tutorial, let us see how to load an resource (eg. image, file ..) which is located inside an Jar file. In this example, we will create a Javafx scene and load an image or text file content in a label.

Running the below code will create a javafx scene which will have two labels and two buttons. Clicking on the button1 (load image) will load the image located inside the jar in the lable1. Clicking on the button2 (load file) will load the content of the text file located in the resources folder in the label2.

Project Structure:

package javaonline.javafx.ui.test;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javaonline.javafx.util.Utils;



public class JavaFxGui extends Application {
	

	public static int WINDOW_WIDTH = 1200;
	public static int WINDOW_HEIGHT = 500;

	

	public static void main(String[] args) {
	
		launch(args);
			}
	

	@Override
	public void start(final Stage stage) {

		stage.setTitle("JavaFx Example");

		GridPane grid = new GridPane();
		grid.setHgap(1);
		grid.setVgap(12);
		grid.setAlignment(Pos.TOP_CENTER);
		ColumnConstraints column = new ColumnConstraints();
		column = new ColumnConstraints();
		column.setPercentWidth(100);
		grid.getColumnConstraints().add(column);

		
		Label lbl = new Label("Image Loading Test");
		
		Label lbl1 = new Label("Text Loading Test");

		Button btn = new Button();
		btn.setText("Load Image");

		Button btn1 = new Button();
		btn1.setText("Load File");

		
		btn.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				
				
				    //Loading Image from classpath 

				      lbl.setGraphic(Utils.setIcon("/image/test.png"));
				      
					   //URL url = this.getClass().getResource("/image/test.png");
					    //lbl.setGraphic(Utils.setIcon(url));

				    
		}
			
		});
		
		
		btn1.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
			
//					load an text file located inside jar
				    	
				   	lbl1.setText(Utils.loadTextFromFile("/resources/test.txt"));
				    	
			
		}
			
		});
		
		
		final VBox vbox= new VBox();
    	vbox.setSpacing(5);
		vbox.getChildren().addAll(lbl,lbl1, btn,btn1);
		grid.add(vbox, 0, 0);
		Scene scene1 = new Scene(grid, 200, 300);
		stage.setScene(scene1);
		//stage.getIcons().add(Utils.setIcon("/image/test.png").getImage());
		stage.getIcons().add(Utils.setImage("/image/test.png"));
		stage.show();

		
	}

	

}

 

Util.java

Code to load image or text file content  which is located inside jar file.

package javaonline.javafx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;

public class Utils {
	
	
	
	
	public static Image setImage(String path) {
		
		InputStream is=Utils.class
				.getResourceAsStream(path);
		return new Image(is);
	}
	
	
	
	//To load image located inside jar
			
		public static ImageView setIcon(String path) {
		
			InputStream is=Utils.class
					.getResourceAsStream(path);
			ImageView iv = new ImageView(new Image(is));

			iv.setFitWidth(100);
			iv.setFitHeight(100);
			return iv;
		}
		
		
		
		
		public static ImageView setIcon(URL url) {
			
				 File file=null;
				    InputStream is = null;
					  
					try {
						file = new File(url.toURI());
						 if(file.isFile())
							 is = new FileInputStream(file);
					} catch (URISyntaxException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				
						
			ImageView iv = new ImageView(new Image(is));

			iv.setFitWidth(100);
			iv.setFitHeight(100);
			return iv;
			// return new ImageView(image);
		}		
		
		
		
		public static String loadTextFromFile(String path) {
			
			InputStream text=null;
	
				try {
					text = (InputStream) Utils.class.getResource(path).getContent();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				java.util.Scanner utilScanner = new java.util.Scanner(text).useDelimiter("\\A");
			    return utilScanner.hasNext() ? utilScanner.next() : "";
			
			
			
			// return new ImageView(image);
		}
		
		
		

 

To test the application, create runnable jar and run the jar file.

 Clicking on the load image button, will load the image on label 1.   Clicking on the load text button will load the content of the text file in the second label.  Please ensure that test.png is placed inside image folder and test.txt is placed in resources folder.

 

Leave a Reply

what are cbd products how much cbd oil orally under tongue cbd oil under tongue natural cbd cbd oil wiki cbd oil after stroke cbd oil cancer testimonials sun raised cbd oil cbd thc ratio for pain infinite cbd coupon code reddit cbd oil for colds try cbd oil free cbd oil capsules for sale cbd oil does it work witg water cbd massachusetts cbd oil red bluff darkside cbd sleep oil cbd oil 25 mg cbd oil in food clinical trials for cbd oil live green hemp cbd will you pass a drug test with cbd oil how does cbd relieve pain choosing the right cbd oil cbd ejuice additive cbd cream for sale pure cbd oil 500mg cbd oil for sale cannablend cbd oil the best cbd oil 2020 cbd hearing loss savage cbd reviews lost lake cbd cbd 700mg 25 best cbd oils natural happiness cbd what cbd products are legal cbd mankato cbd oil sarasota fl discovery cbd health hut cbd oil highway 100 cbd oil uses and benefits shop best cbd oil to buy cbd tachycardia cannabis oil cancer where to buy shops for lease melbourne cbd

strong male enhancement pills best rated sex pills on gastations male sexual enhancement pill best liquor store sex pills african superman male enhancement pills can blood pressure pills kill your sex drive alphamale xl male enhancement penis hot after pills tauler smith male enhancement hypnotic penis enlargement vx4 male enhancement boost rx male enhancement ingredients yellow jacket pills shark tank episode male enhancement same day supplements review male enhancement sleeve extender pro v male enhancement pills vitamin d and zinc supplement nitrous oxide pills gnc vesele supplement does rock hard weekend pill work new japnese sex pills for men ayurvedic flaccid penis enlargement crazy supplement penis pills hellmoo penis enlargement surgery in belgium common chinese enhancement sex drug instant male enhancement pills what is viganmor sex pills steel ed pills chinese street fighter sex pills nitrate pills blood pressure viagra pills for sale australia esquire penis enlargement true male enhancement pills number 1 penis enlargement pills male enhancement supplement pills super tiger x pill review gnc male enhancement pills side effects sex pill for men over the counter all natural male breast enhancement pills enlarged prostrate erectile dysfunction performance male enhancement pill review male enhancement creme just released chinese male enhancement pills male enhancement lavestra

new diets for quick weight loss average weight loss for male on southbeach diet 10 pound weight loss diet cinch weight loss diet herbal supplements to lose weight healthy organic weight loss pills diet food plans to lose weight fast maintainable weight loss diet proper diet to lose weight fast label on back of keto ultra diet pills diet eating plan to lose weight fast weight loss pills uk how to lose weight with mediterranean diet weight loss diet naturally what protein supplement is best for weight loss keto indian diet recipes diet for weight loss and high blood pressure diet pill lose weight fast 1 effective weight loss pills thermofight weight loss pills best weight loss pills with ephedrine do detox pills work for weight loss 30 day trial weight loss pills probiotics supplements weight loss garcinia cambogia weight loss pills at walmart green tea weight loss tablets keto burn ketosis weight loss pills nature driven keto diet recipes taco weight loss pills approved by ncaa how do water pills for weight loss work herbalife weight loss diet chart what is a good healthy diet plan to lose weight weight loss model diet weight loss on dukan diet strict weight loss diet menu hours between green tea weight loss pills fast weight loss on ketogenic diet weight loss pills to lose weight fast meta analysis ketogenic diet weight loss high carb low fat diet weight loss previously hadweight losssurgery and keto diet what is the best weight loss pill for 2020 weight loss diet what not to eat male vegan weight loss diet weight loss aids diet stoner diet to lose weight