blob: ce26c6c8a81b71a5a857e95e878bf37d75c50159 [file] [log] [blame]
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01001// Copyright 2014 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14package com.google.devtools.build.lib.util;
15
16import static java.nio.charset.StandardCharsets.UTF_8;
17
18import com.google.common.io.ByteStreams;
19
20import java.io.IOException;
21import java.io.InputStream;
22
23/**
24 * A little utility to load resources (property files) from jars or
25 * the classpath. Recommended for longer texts that do not fit nicely into
26 * a piece of Java code - e.g. a template for a lengthy email.
27 */
28public final class ResourceFileLoader {
29
30 private ResourceFileLoader() {}
31
32 /**
33 * Loads a text resource that is located in a directory on the Java classpath that
34 * corresponds to the package of <code>relativeToClass</code> using UTF8 encoding.
35 * E.g.
36 * <code>loadResource(Class.forName("com.google.foo.Foo", "bar.txt"))</code>
37 * will look for <code>com/google/foo/bar.txt</code> in the classpath.
38 */
39 public static String loadResource(Class<?> relativeToClass, String resourceName)
40 throws IOException {
41 ClassLoader loader = relativeToClass.getClassLoader();
42 // TODO(bazel-team): use relativeToClass.getPackage().getName().
43 String className = relativeToClass.getName();
44 String packageName = className.substring(0, className.lastIndexOf('.'));
45 String path = packageName.replace('.', '/');
46 String resource = path + '/' + resourceName;
47 InputStream stream = loader.getResourceAsStream(resource);
48 if (stream == null) {
49 throw new IOException(resourceName + " not found.");
50 }
51 try {
52 return new String(ByteStreams.toByteArray(stream), UTF_8);
53 } finally {
54 stream.close();
55 }
56 }
57}