ResourceNS.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import java.io.InputStream;
  2. import java.io.InputStreamReader;
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. class ResourceNS
  6. {
  7. public static void main(String args[])
  8. {
  9. ResourceNS res = new ResourceNS();
  10. res.displayResourceText();
  11. }
  12. public void displayResourceText()
  13. {
  14. /*
  15. * Since Java SE 9, invoking getResourceXXX on a class in a named
  16. * module will only locate the resource in that module, it will
  17. * not search the class path as it did in previous release. So when
  18. * you use Class.getClassLoader().getResource() it will attempt to
  19. * locate the resource in the module containing the ClassLoader,
  20. * possibly something like:
  21. * jdk.internal.loader.ClassLoaders.AppClassLoader
  22. * which is probably not the module that your resource is in, so it
  23. * returns null.
  24. *
  25. * You have to make java 9+ search for the file in your module.
  26. * Do that by changing Class to any class defined in your module in
  27. * order to make java use the proper class loader.
  28. */
  29. // Namespaces are relative, use leading '/' for full namespace
  30. InputStream is =
  31. ResourceNS.class.getResourceAsStream("/ns/ns1/HelloWorld.txt");
  32. // C++: cout << is.readline(); // oh, well !
  33. InputStreamReader isr = new InputStreamReader(is);
  34. BufferedReader reader = new BufferedReader(isr);
  35. String out = "";
  36. try{
  37. out = reader.readLine();
  38. } catch(IOException e) {
  39. e.printStackTrace();
  40. System.out.println(e);
  41. }
  42. System.out.println(out);
  43. }
  44. }