Skip to content

Resources

Łukasz Stypka edited this page Jul 21, 2013 · 1 revision

Have you ever had a problem with the resource? Everyone had. The solution of your problems is the Resources class!

findFilePaths

There are two methods responsible for finding resources path in Resources class. public static List<Path> findFilePaths(String fileName) public static List<Path> findFilePaths(String startingDir, String fileName)

The first one starts searching from the root directory of the application. Suppose we have the following directory hierarchy:

-- \
    |-- src
    |   |-- main
    |   |   |-- java
    |   |   |-- resources
    |   |   |   |-- testFile.txt
    |   |-- test
    |   |   |-- java
    |   |   |-- resources
    |-- target
    |   |-- classes
    |   |   |-- testFile.txt

By calling the List<Path> paths = Resources.findFilePaths("testFile.txt") method, you will receive:

src\main\resources\testFile.txt
target\classes\testFile.txt

The second method allows you to specify the directory from which you want to start the search.

List<Path> paths = Resources.findFilePaths("src/main", "testFile.txt")
// paths : src\main\resources\testFile.txt

asFile, asListOfLines, asString, asInputStream

Once you have found the path, you can get content of the resource as

  • file: File file = Resources.asFile(paths.get(0));
  • list of lines List<String> listOfLines = Resources.asListOfLines(paths.get(0));
  • String String asString = Resources.asString(paths.get(0));
  • input stream InputStream is = Resources.asInputStream(paths.get(0));

All presented methods allow also the getting Internet resource. Thanks to them you can save the Internet resource onto HDD or get it as file, String, inputStream without too much trouble. Suppose you want to download a file from the address: www.jsolve.pl/logo.jpg You can get the resource as:

  • file
URL urlToResource = new URL("www.jsolve.pl/logo.jpg");
File logo = Resources.asFile(urlToResource, "D:\\img\\logo.jpg");
// The logo.jpg from www.jsolve.pl/logo.jpg will be stored into "D:\\img\\logo.jpg" and you'll receive handler to this file.
  • list of lines
URL urlToResource = new URL("www.jsolve.pl/logo.jpg");
InputStream is = Resources.asInputStream(urlToResource);
  • String
URL urlToResource = new URL("www.jsolve.pl/logo.jpg");
String content = Resources.asString(urlToResource);
  • input stream
URL urlToResource = new URL("www.jsolve.pl/logo.jpg");
InputStream is = Resources.asInputStream(urlToResource);

closeStream

Well-known problem when working with streams is their closing. Whenever you want to close the stream you are forced to the following code:

try {
        // some operations
} finally {
	try {
		is.close();
	} catch (IOException e) {
		// throw another exception
	}
}

Instead, you can call the void closeStream(Closeable closeable) method:

try {
        // some operations
} finally {
	Resources.closeStream(is);
}

Clone this wiki locally