• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. 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 distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package com.google.common.io;
16 
17 import static com.google.common.base.Preconditions.checkArgument;
18 import static com.google.common.base.Preconditions.checkNotNull;
19 
20 import com.google.common.annotations.Beta;
21 import com.google.common.annotations.GwtIncompatible;
22 import com.google.common.base.Charsets;
23 import com.google.common.base.MoreObjects;
24 import com.google.common.collect.Lists;
25 import com.google.errorprone.annotations.CanIgnoreReturnValue;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.OutputStream;
29 import java.net.URL;
30 import java.nio.charset.Charset;
31 import java.util.List;
32 import org.checkerframework.checker.nullness.qual.Nullable;
33 
34 /**
35  * Provides utility methods for working with resources in the classpath. Note that even though these
36  * methods use {@link URL} parameters, they are usually not appropriate for HTTP or other
37  * non-classpath resources.
38  *
39  * <p>All method parameters must be non-null unless documented otherwise.
40  *
41  * @author Chris Nokleberg
42  * @author Ben Yu
43  * @author Colin Decker
44  * @since 1.0
45  */
46 @Beta
47 @GwtIncompatible
48 @ElementTypesAreNonnullByDefault
49 public final class Resources {
Resources()50   private Resources() {}
51 
52   /**
53    * Returns a {@link ByteSource} that reads from the given URL.
54    *
55    * @since 14.0
56    */
asByteSource(URL url)57   public static ByteSource asByteSource(URL url) {
58     return new UrlByteSource(url);
59   }
60 
61   /** A byte source that reads from a URL using {@link URL#openStream()}. */
62   private static final class UrlByteSource extends ByteSource {
63 
64     private final URL url;
65 
UrlByteSource(URL url)66     private UrlByteSource(URL url) {
67       this.url = checkNotNull(url);
68     }
69 
70     @Override
openStream()71     public InputStream openStream() throws IOException {
72       return url.openStream();
73     }
74 
75     @Override
toString()76     public String toString() {
77       return "Resources.asByteSource(" + url + ")";
78     }
79   }
80 
81   /**
82    * Returns a {@link CharSource} that reads from the given URL using the given character set.
83    *
84    * @since 14.0
85    */
asCharSource(URL url, Charset charset)86   public static CharSource asCharSource(URL url, Charset charset) {
87     return asByteSource(url).asCharSource(charset);
88   }
89 
90   /**
91    * Reads all bytes from a URL into a byte array.
92    *
93    * @param url the URL to read from
94    * @return a byte array containing all the bytes from the URL
95    * @throws IOException if an I/O error occurs
96    */
toByteArray(URL url)97   public static byte[] toByteArray(URL url) throws IOException {
98     return asByteSource(url).read();
99   }
100 
101   /**
102    * Reads all characters from a URL into a {@link String}, using the given character set.
103    *
104    * @param url the URL to read from
105    * @param charset the charset used to decode the input stream; see {@link Charsets} for helpful
106    *     predefined constants
107    * @return a string containing all the characters from the URL
108    * @throws IOException if an I/O error occurs.
109    */
toString(URL url, Charset charset)110   public static String toString(URL url, Charset charset) throws IOException {
111     return asCharSource(url, charset).read();
112   }
113 
114   /**
115    * Streams lines from a URL, stopping when our callback returns false, or we have read all of the
116    * lines.
117    *
118    * @param url the URL to read from
119    * @param charset the charset used to decode the input stream; see {@link Charsets} for helpful
120    *     predefined constants
121    * @param callback the LineProcessor to use to handle the lines
122    * @return the output of processing the lines
123    * @throws IOException if an I/O error occurs
124    */
125   @CanIgnoreReturnValue // some processors won't return a useful result
126   @ParametricNullness
readLines( URL url, Charset charset, LineProcessor<T> callback)127   public static <T extends @Nullable Object> T readLines(
128       URL url, Charset charset, LineProcessor<T> callback) throws IOException {
129     return asCharSource(url, charset).readLines(callback);
130   }
131 
132   /**
133    * Reads all of the lines from a URL. The lines do not include line-termination characters, but do
134    * include other leading and trailing whitespace.
135    *
136    * <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code
137    * Resources.asCharSource(url, charset).readLines()}.
138    *
139    * @param url the URL to read from
140    * @param charset the charset used to decode the input stream; see {@link Charsets} for helpful
141    *     predefined constants
142    * @return a mutable {@link List} containing all the lines
143    * @throws IOException if an I/O error occurs
144    */
readLines(URL url, Charset charset)145   public static List<String> readLines(URL url, Charset charset) throws IOException {
146     // don't use asCharSource(url, charset).readLines() because that returns
147     // an immutable list, which would change the behavior of this method
148     return readLines(
149         url,
150         charset,
151         new LineProcessor<List<String>>() {
152           final List<String> result = Lists.newArrayList();
153 
154           @Override
155           public boolean processLine(String line) {
156             result.add(line);
157             return true;
158           }
159 
160           @Override
161           public List<String> getResult() {
162             return result;
163           }
164         });
165   }
166 
167   /**
168    * Copies all bytes from a URL to an output stream.
169    *
170    * @param from the URL to read from
171    * @param to the output stream
172    * @throws IOException if an I/O error occurs
173    */
copy(URL from, OutputStream to)174   public static void copy(URL from, OutputStream to) throws IOException {
175     asByteSource(from).copyTo(to);
176   }
177 
178   /**
179    * Returns a {@code URL} pointing to {@code resourceName} if the resource is found using the
180    * {@linkplain Thread#getContextClassLoader() context class loader}. In simple environments, the
181    * context class loader will find resources from the class path. In environments where different
182    * threads can have different class loaders, for example app servers, the context class loader
183    * will typically have been set to an appropriate loader for the current thread.
184    *
185    * <p>In the unusual case where the context class loader is null, the class loader that loaded
186    * this class ({@code Resources}) will be used instead.
187    *
188    * @throws IllegalArgumentException if the resource is not found
189    */
190   @CanIgnoreReturnValue // being used to check if a resource exists
191   // TODO(cgdecker): maybe add a better way to check if a resource exists
192   // e.g. Optional<URL> tryGetResource or boolean resourceExists
getResource(String resourceName)193   public static URL getResource(String resourceName) {
194     ClassLoader loader =
195         MoreObjects.firstNonNull(
196             Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader());
197     URL url = loader.getResource(resourceName);
198     checkArgument(url != null, "resource %s not found.", resourceName);
199     return url;
200   }
201 
202   /**
203    * Given a {@code resourceName} that is relative to {@code contextClass}, returns a {@code URL}
204    * pointing to the named resource.
205    *
206    * @throws IllegalArgumentException if the resource is not found
207    */
208   @CanIgnoreReturnValue // being used to check if a resource exists
getResource(Class<?> contextClass, String resourceName)209   public static URL getResource(Class<?> contextClass, String resourceName) {
210     URL url = contextClass.getResource(resourceName);
211     checkArgument(
212         url != null, "resource %s relative to %s not found.", resourceName, contextClass.getName());
213     return url;
214   }
215 }
216