View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.util;
15  
16  import ch.qos.logback.core.spi.ContextAware;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.io.InputStreamReader;
22  import java.net.MalformedURLException;
23  import java.net.URL;
24  import java.net.URLConnection;
25  
26  public class FileUtil {
27  
28  
29    public static URL fileToURL(File file) {
30      try {
31        return file.toURI().toURL();
32      } catch (MalformedURLException e) {
33        throw new RuntimeException("Unexpected exception on file ["+file+"]", e);
34      }
35    }
36  
37    static public boolean isParentDirectoryCreationRequired(File file) {
38      File parent = file.getParentFile();
39      if (parent != null && !parent.exists()) {
40        return true;
41      } else {
42        return false;
43      }
44    }
45  
46    static public boolean createMissingParentDirectories(File file) {
47      File parent = file.getParentFile();
48      if (parent == null) {
49        throw new IllegalStateException(file + " should not have a null parent");
50      }
51      if (parent.exists()) {
52        throw new IllegalStateException(file + " should not have existing parent directory");
53      }
54      return parent.mkdirs();
55    }
56  
57  
58    static public String resourceAsString(ContextAware ca, ClassLoader classLoader, String resourceName) {
59      URL url = classLoader.getResource(resourceName);
60      if (url == null) {
61        ca.addError("Failed to find resource [" + resourceName + "]");
62        return null;
63      }
64  
65      InputStreamReader isr = null;
66      try {
67        URLConnection urlConnection = url.openConnection();
68        urlConnection.setUseCaches(false);
69        isr = new InputStreamReader(urlConnection.getInputStream());
70        char[] buf = new char[128];
71        StringBuilder builder = new StringBuilder();
72        int count = -1;
73        while ((count = isr.read(buf, 0, buf.length)) != -1) {
74          builder.append(buf, 0, count);
75        }
76        return builder.toString();
77      } catch (IOException e) {
78        ca.addError("Failled to open " + resourceName, e);
79      } finally {
80        if(isr != null) {
81          try {
82            isr.close();
83          } catch (IOException e) {
84            // ignore
85          }
86        }
87      }
88      return null;
89    }
90  }