0

I am rewriting my classes that loads resources inside of my game. My professor told us to try not to use "/" slash sign in our Strings/File/URL when loading our resources. I am using Classname.class.getResource(someString) to get URLs so I can load my resources which works great ( see code below). I read the Oracle Docs for class.getResource() and there I have to use "/". I would like to know if there's a better way for loading resources (images and audio files mostly) than using ClassName.class.getResource()? I don't have any speed or memory requirements. Here an example of how I load an BufferedImage.

    try {
        // Example path = "/menu/background2.png"
        sourceImage = ImageIO.read(ResourceManager.class.getResource(path));


    } catch (IOException e) {
        System.out.println("Failed to load: " + path);

        e.printStackTrace();

    }
Towni0
  • 87
  • 1
  • 6
  • 1
    That is the recommended way. – icza Aug 29 '14 at 10:46
  • 1
    When loading resources you must use `/` as this is part of the URL requirements. On Windows systems, file paths with `/` are automatically converted to "\", but "\" is not automatically converted on *nix systems. For File paths you should consider using `File.pathSeparator` where possible, but as I stated, it's not required – MadProgrammer Aug 29 '14 at 10:58

2 Answers2

1

I read the Oracle Docs for class.getResource() and there I have to use "/" Obviously you have to use / for windows or \ for linux as the file separator. The file separator is use to navigate inside a directory.

Suppose you have a file inside mydirectory/filename and you have kept it under the resources folder of your project. The way to read this will be either

URL url = className.class.getClassLoader().getResource("/mydirectory/filename");

or

InputStream is = className.class.getClassLoader()
                                .getResourceAsStream("/mydirectory/filename");

Or

URL url = Thread.currentThread().getContextClassLoader()
                                .getResource("/mydirectory/filename");

Or

InputStream is  = Thread.currentThread().getContextClassLoader()
                                  .getResourceAsStream("/mydirectory/filename");

/ will be used to browse inside the directories.

SparkOn
  • 8,806
  • 4
  • 29
  • 34
1

You can use slashes in the path, but not backslashes, because you are not using file path, rather than path in the classpath. Don't use leading slash if you want the relative path from the class. When you use file path then you can use File.separator to in path, however in URLs you can still use a slash. More over File.separator usage is wrong in URLs, because it will not work on Windows systems that requires escape a backslash symbol to use in URL.