4

I am building a project and need to use WebEngine class. So I have 2 projects, MainA and SecondB. The SecondB project is in dependency to MainA, so after building it SecondB becomes a jar file in the MainA libs folder.
Now. I need to open a abc.html file that is under SecondB resources. When testing it locally it works, when building an app and deploying it on server it fails (probably because it is in SecondB jar file). So the code I am using is:

WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();  
ClassLoader classLoader = getClass().getClassLoader();
String s = classLoader.getResource("subfolder/abc.html").toExternalForm();
webEngine.load(s);

The method classLoader.getResource("subfolder/abc.html").toExternalForm();returns a normal url when running the code localy and something like:

file:jar:C:/Something/MainA/libs/SecondB.jar!/subfolder/abc.html

Do you have any ideas how to load this file from a jar? I tried several options I found on SO, but without success

kamil.rak
  • 1,378
  • 1
  • 14
  • 28

3 Answers3

1

You can create a "resources" package and copy your files to this package and for accessing your file path for example an html you can use this: getClass().getResource("/resources/abc.html").toURI().toString() this provides to get your files url in your created jar. Hope it is useful.

GltknBtn
  • 512
  • 6
  • 13
  • I already have a resource package in my SecondB project and that is where the file is. Or maybe you mean put it in the Main projekt under resources? I considered that, but do not like this solution to be honest. – kamil.rak Feb 07 '17 at 14:06
  • The `/resources` subdirectory is redundant unless you want it that way. But there are usually many subdirectories inside `/resource`. So I'd recommend `...getResource("/doc/abc.html")`, etc – mk7 Jun 21 '18 at 04:18
0

To me, I did this

String fileloc = "/docs/help/userguide.html";
...
String fullLink = getClass().getResource(fileloc).toExternalForm();
...

I store the html file inside the resources folder. e.g./resources/docs/help/userguide.html

As I run the compiled jar, it has no problem being loaded up by javafx webengine.

mk7
  • 150
  • 1
  • 9
0

I think you are almost there, you can read the url via InputStream into String, and use WebEngine.loadContent to load the String content, provided you only want to display single page. If your page reference to other files (javascript/css), it will not work.

So, it is better to this, while your JavaFX app is started, you copy out the whole resource folder into your local file system, then use the WebEngine to load the HTML file, this should work better.

Sam YC
  • 10,725
  • 19
  • 102
  • 158