View Javadoc
1   package org.opentrafficsim.base;
2   
3   import java.io.InputStream;
4   import java.net.URI;
5   import java.net.URISyntaxException;
6   
7   /**
8    * Resource utility.
9    * <p>
10   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
11   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
12   * </p>
13   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
14   * @author <a href="https://tudelft.nl/staff/p.knoppers-1">Peter Knoppers</a>
15   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
16   */
17  public final class Resource
18  {
19  
20      /** Constructor. */
21      private Resource()
22      {
23          //
24      }
25  
26      /**
27       * Obtains stream for resource, either in IDE or java.
28       * @param name String; name of resource
29       * @return the resolved input stream
30       */
31      public static InputStream getResourceAsStream(final String name)
32      {
33          InputStream stream = Resource.class.getResourceAsStream(name);
34          if (stream != null)
35          {
36              return stream;
37          }
38          stream = Resource.class.getResourceAsStream("/resources" + name);
39          if (stream != null)
40          {
41              return stream;
42          }
43          throw new RuntimeException("Unable to load resource " + name);
44      }
45      
46      /**
47       * Obtains URI for resource, either in IDE or java.
48       * @param name String; name of resource
49       * @return the resolved URI
50       * @throws URISyntaxException when the file name is malformed.
51       */
52      public static URI getResourceAsUri(final String name) throws URISyntaxException
53      {
54          InputStream stream = Resource.class.getResourceAsStream(name);
55          if (stream != null)
56          {
57              return Resource.class.getResource(name).toURI();
58          }
59          stream = Resource.class.getResourceAsStream("/resources" + name);
60          if (stream != null)
61          {
62              return Resource.class.getResource("/resources" + name).toURI();
63          }
64          throw new RuntimeException("Unable to load resource " + name);
65          
66      }
67  
68  }