1

I have a simple question: I am working on a JavaFX application and need a reference to a specific class. I looked my problem up on the Internet and found out that I had to use getResourceAsStream instead of getResource. I looked up both methods and only found one difference. The getResourceAsStream returns an InputStream and the getResource returns an URL. But what is the difference, why is the InputStream working for me and the URL not? I never really worked with Stream, any explanations are greatly appreciated.

getResource(String name) getResourceAsStream(String name)

SDJ
  • 4,083
  • 1
  • 17
  • 35
Tom Buente
  • 11
  • 5
  • The resource URL may be packed into a jar file so you won't be able to resolve it; the stream already contains the data you're trying to access. – daniu Jun 20 '19 at 11:27
  • 2
    Both methods point work with the exact same resource. Using `clazz.getResource(p).openStream()` should have the same result as using `clazz.getResourceAsStream(p)`. If one is problematic and the other not, something else seems to be wrong with your code (provide a [mcve]). Perhaps you're using this with `FXMLLoader` and pass both values to the `load` method of a loader instance? In that case note that one of the methods is `static` and the other not so one of them uses the loader instance you created and the other one creates a new one. (Pass the url via loader constructor and call `load()`.) – fabian Jun 20 '19 at 11:48
  • ```FXMLLoader fxmlLoader = new FXMLLoader(); Parent root = fxmlLoader.load(getClass().getResourceAsStream("stochastik.fxml")); controller = fxmlLoader.getController(); stage.setTitle("Stochastikrechner von Leon und Tom");``` – Tom Buente Jun 20 '19 at 11:59
  • Please [edit] your question to add information (if it's an example make sure it's a [mre]). – Slaw Jun 20 '19 at 19:24
  • "_I never really worked with `Stream` [...]_": If by `Stream` you mean `java.util.stream.Stream`, then note that an `InputStream` is not a `Stream`. – Slaw Jun 20 '19 at 19:25
  • Possible duplicate of [What is the difference between Class.getResource() and ClassLoader.getResource()?](https://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource) – Miss Chanandler Bong Jun 26 '19 at 12:31

1 Answers1

0

getResource() will work only if your WAR is exploded. In OpenShift, this is not the case so you should be using getResourceAsStream() to get that work.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Krim_0
  • 11
  • 1