Accessing a resource file from a compiled JAR archive

One issue that I am facing involves the project structure of my Maven Java project. It follows a typical layout:

src/main/java - project .java files      
src/main/resources - project resources (log4j2.xml)
src/test/java - .java files for tests
src/test/resources - testng.xml file

In the src/main/java directory, there is a package containing JavaScript files (scripts that are executed programmatically in Java code) located at: src/main/java/js/scripts/

While I can access the *.js files within the 'scripts' folder when running tests using FileUtils.readFileToString(new File(pathTo_jsFile)), this functionality ceases to work after compiling the project with Maven.

  1. I am unable to compile the files to be placed inside the existing package (/js/scripts/) – the only way I have found to add non-Java files to the .jar is by including them as resources in the pom.xml, but then they are added to the root of the .jar file.

  2. I am also unable to read anything from within the .jar file.

Answer №1

To start, make sure to place your JavaScript files in the src/main/resources directory. When building with Maven, these files will be automatically included in the .jar file without any additional configuration needed. You can maintain your folder structure within the resources folder as well.

Next, you can access these resources in Java using the ClassLoader:

getClass().getClassLoader().getResourceAsStream("js/scripts/myScriptfile.js");

This code snippet allows you to retrieve the JavaScript file as an input stream. If you would rather get the URL of the file (which also works when it's packaged inside a JAR file), simply replace getResourceAsStream(...) with getResource(...).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the best method for accessing and utilizing an existing file effortlessly

As a newcomer to PHP, I have successfully learned how to upload a file from a list using the following code: var file = e.target.files[0]; alert(file); This code returns an [object File], indicating that the file has been uploaded. Now, my question is: ...

How can TypeORM be used to query a ManyToMany relationship with a string array input in order to locate entities in which all specified strings must be present in the related entity's column?

In my application, I have a User entity that is related to a Profile entity in a OneToOne relationship, and the Profile entity has a ManyToMany relationship with a Category entity. // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn( ...

Retrieve data from a JSON file to assign to a variable, then access another API to retrieve a second

I am completely new to the world of javascript and json. My previous experience with javascript was quite minimal, about 12 years ago. So, please bear with me as I try to explain my current issue. The problem I am facing involves retrieving a second API UR ...

Discover a helpful tip for using Pentadactyl with StackExchange's voting buttons

Does anyone know how to enable hinting for voting arrows on StackExchange using Pentadactyl (a fork of Vimperator)? I've tried removing my .pentadactylrc file and restarting Firefox, but still can't figure out how to upvote questions and answers ...

Comparing Canvas and CSS3 for Website Development

Many discussions focus on comparing games with high levels of interaction, but my project involves a web application that manipulates objects individually. These objects can be images or text, and they can be replaced, resized, rotated, zoomed in, and dele ...

Tips for effortlessly enlarging an element

When you click on "#sidebarnav>li", the following happens: 1) The second child of it - <ul> element will expand and its class toggles between "collapse" and "collapse in". 2) "#sidebarnav>li" will receive the "active" class. 3) The "aria-ex ...

Utilizing AngularJS: Using ng-click with ng-repeat to retrieve all data simultaneously

Having a simple ng-repeat: <div ng-repeat="x in names"> <h4>{{x.productid}}</h4> <h4>{{x.newquantity}}</h4> <h4>{{x.total}}</h4> <button ng-click="addInfoAboutOrder(x)">Add Info</button> ...

script loop causing an embedded form

While trying to include a Hubspot embedded form on a page using a script, I encountered an issue. I utilized onMounted to ensure the form is displayed correctly. However, upon leaving and re-entering the component where the form is located, an additional b ...

Retrieve items within an array of objects in MongoDB using an array of IDs (using the $in operator in aggregation)

In my MongoDB database, I have a collection of stores [ { "_id" : ObjectId("6043adb043707c034d5363b7"), "shopId" : "shopid1", "appId" : "777", "shopItems" : [ { ...

utilize javascript variables within an HTML document

I keep encountering a strange error (Express 400 Error: Bad Request) Some lines are translated to the variable value, while others just output an error. This is an example of my code: exports.add_comment = function(req, res){ var id = req.params.id; ...

Using an HTTP request to switch frames in Arsenic

Currently working on a project using arsenic (the async version of selenium) and I'm faced with the challenge of changing the context to an iframe. Unlike Selenium, Arsenic doesn't have the switchTo functionality built-in, but it does allow for c ...

Is it possible to utilize a controller within a different controller?

As I work on developing an application, I am faced with the challenge of using controller functions within another controller function. Is it possible to achieve this or not? Use-case: My goal is to verify in the User collection (using mongoDB) if a user ...

When receiveMessage is triggered, the FCM push notification fails to refresh the view

After following this helpful tutorial on Push Notifications with Angular 6 + Firebase Cloud Messaging, everything is working perfectly. I am able to receive notifications when using another browser. To ensure that my notification list and the length of no ...

My loop encountered an 'Undefined' error while attempting to retrieve an object from a JSON file

Hey everyone, I could use some help with a problem I'm having in my for loop. The issue is that I keep getting an "undefined" word in the output of my loop. I am trying to retrieve objects from a JSON file and the loop itself seems to be working corre ...

I'm finding it difficult to grasp the purpose of $inject within controllers

I'm feeling completely lost when it comes to understanding inject in Angular. I can't seem to grasp where it should be utilized and its purpose. Is it specifically tied to factory methods, as outlined here? myController.$inject = ['$scope&a ...

Utilizing JavaScript for parallax horizontal scrolling (identifying optimal 50% of screen)

I have successfully implemented this code for vertical scrolling: $('.flapleftclass').css('top',(0+(scrolled*0.5))+'px'); This method works well because I am referencing to the top position. However, when it comes to horizon ...

The data type 'void' cannot be assigned to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'

Can you assist me in understanding what has occurred and provide guidance on the necessary steps to resolve it? I am currently working on a website where I am in need of hooks to update the state. The issue seems to be related to the onClick events within ...

Automate the login process on a website by utilizing saved passwords in the browser with Selenium

I am facing an issue with using Selenium to select my saved logins and passwords in Firefox. I have successfully specified my profile and instructed Selenium to create a temporary profile with the necessary files, but when I try to login with my saved cr ...

Is it possible to connect or link two collections in spring-data-mongodb as ManyToMany similar to a relational database management system (R

I encountered an issue while trying to implement a sample example from https://github.com/szerhusenBC/jwt-spring-security-demo/ using mongodb as my backend. The problem originates from the code in JwtUserFactory.java. return authorities.stream() ...

Access the content of each cell in a table using JavaScript

I need help with a scenario involving a table that has 4 rows, where the 4th row contains a textbox. When the "onchange" event of the textbox is activated, I want to retrieve the data from the cells in that specific row and transfer it to another table. It ...