1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.jakewharton.disklrucache;
18 
19 import java.io.Closeable;
20 import java.io.File;
21 import java.io.IOException;
22 import java.io.Reader;
23 import java.io.StringWriter;
24 import java.nio.charset.Charset;
25 
26 /** Junk drawer of utility methods. */
27 final class Util {
28   static final Charset US_ASCII = Charset.forName("US-ASCII");
29   static final Charset UTF_8 = Charset.forName("UTF-8");
30 
Util()31   private Util() {
32   }
33 
readFully(Reader reader)34   static String readFully(Reader reader) throws IOException {
35     try {
36       StringWriter writer = new StringWriter();
37       char[] buffer = new char[1024];
38       int count;
39       while ((count = reader.read(buffer)) != -1) {
40         writer.write(buffer, 0, count);
41       }
42       return writer.toString();
43     } finally {
44       reader.close();
45     }
46   }
47 
48   /**
49    * Deletes the contents of {@code dir}. Throws an IOException if any file
50    * could not be deleted, or if {@code dir} is not a readable directory.
51    */
deleteContents(File dir)52   static void deleteContents(File dir) throws IOException {
53     File[] files = dir.listFiles();
54     if (files == null) {
55       throw new IOException("not a readable directory: " + dir);
56     }
57     for (File file : files) {
58       if (file.isDirectory()) {
59         deleteContents(file);
60       }
61       if (!file.delete()) {
62         throw new IOException("failed to delete file: " + file);
63       }
64     }
65   }
66 
closeQuietly( Closeable closeable)67   static void closeQuietly(/*Auto*/Closeable closeable) {
68     if (closeable != null) {
69       try {
70         closeable.close();
71       } catch (RuntimeException rethrown) {
72         throw rethrown;
73       } catch (Exception ignored) {
74       }
75     }
76   }
77 }
78