FileUtils.java

  1. /**
  2.  *
  3.  * Copyright the original author or authors
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack.util;

  18. import java.io.BufferedReader;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.FileNotFoundException;
  22. import java.io.FileOutputStream;
  23. import java.io.FileReader;
  24. import java.io.FileWriter;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.io.InputStreamReader;
  28. import java.io.Reader;
  29. import java.net.MalformedURLException;
  30. import java.net.URI;
  31. import java.net.URL;
  32. import java.nio.charset.StandardCharsets;
  33. import java.util.ArrayList;
  34. import java.util.List;
  35. import java.util.Set;
  36. import java.util.logging.Level;
  37. import java.util.logging.Logger;

  38. public final class FileUtils {

  39.     private static final Logger LOGGER = Logger.getLogger(FileUtils.class.getName());

  40.     public static InputStream getInputStreamForClasspathFile(String path) {
  41.         return getInputStreamForClasspathFile(path, null);
  42.     }

  43.     public static InputStream getInputStreamForClasspathFile(String path, ClassLoader loader) {
  44.         try {
  45.             return getStreamForClasspathFile(path, loader);
  46.         } catch (IOException e) {
  47.             LOGGER.log(Level.FINE, "Suppressed IOException in getInputStreamForClasspathFile", e);
  48.             return null;
  49.         }
  50.     }

  51.     public static InputStream getStreamForClasspathFile(String path, ClassLoader loader) throws IOException {
  52.         // Get an array of class loaders to try loading the providers files from.
  53.         List<ClassLoader> classLoaders = getClassLoaders();
  54.         if (loader != null) {
  55.             classLoaders.add(0, loader);
  56.         }
  57.         for (ClassLoader classLoader : classLoaders) {
  58.             InputStream is = classLoader.getResourceAsStream(path);

  59.             if (is != null) {
  60.                 return is;
  61.             }
  62.         }
  63.         throw new IOException("Unable to get '" + path + "' from classpath. Tried ClassLoaders:" + classLoaders);
  64.     }

  65.     public static InputStream getStreamForUri(URI uri, ClassLoader loader) throws IOException {
  66.         String protocol = uri.getScheme();
  67.         if (protocol.equals("classpath")) {
  68.             String path = uri.getSchemeSpecificPart();
  69.             return getStreamForClasspathFile(path, loader);
  70.         }

  71.         URL url = uri.toURL();
  72.         return url.openStream();
  73.     }

  74.     /**
  75.      * Returns default classloaders.
  76.      *
  77.      * @return a List of ClassLoader instances.
  78.      */
  79.     public static List<ClassLoader> getClassLoaders() {
  80.         ClassLoader[] classLoaders = new ClassLoader[2];
  81.         classLoaders[0] = FileUtils.class.getClassLoader();
  82.         classLoaders[1] = Thread.currentThread().getContextClassLoader();

  83.         // Clean up possible null values. Note that #getClassLoader may return a null value.
  84.         List<ClassLoader> loaders = new ArrayList<ClassLoader>(classLoaders.length);
  85.         for (ClassLoader classLoader : classLoaders) {
  86.             if (classLoader != null) {
  87.                 loaders.add(classLoader);
  88.             }
  89.         }
  90.         return loaders;
  91.     }

  92.     public static boolean addLines(String uriString, Set<String> set) throws MalformedURLException, IOException {
  93.         URI uri = URI.create(uriString);
  94.         InputStream is = getStreamForUri(uri, null);
  95.         InputStreamReader sr = new InputStreamReader(is, StandardCharsets.UTF_8);
  96.         BufferedReader br = new BufferedReader(sr);
  97.         try {
  98.             String line;
  99.             while ((line = br.readLine()) != null) {
  100.                 set.add(line);
  101.             }
  102.         }
  103.         finally {
  104.             br.close();
  105.         }
  106.         return true;
  107.     }

  108.     /**
  109.      * Reads the contents of a File.
  110.      *
  111.      * @param file TODO javadoc me please
  112.      * @return the content of file or null in case of an error
  113.      * @throws IOException if an I/O error occurred.
  114.      */
  115.     @SuppressWarnings("DefaultCharset")
  116.     public static String readFileOrThrow(File file) throws IOException {
  117.         try (Reader reader = new FileReader(file)) {
  118.             char[] buf = new char[8192];
  119.             int len;
  120.             StringBuilder s = new StringBuilder();
  121.             while ((len = reader.read(buf)) >= 0) {
  122.                 s.append(buf, 0, len);
  123.             }
  124.             return s.toString();
  125.         }
  126.     }

  127.     public static String readFile(File file) {
  128.         try {
  129.             return readFileOrThrow(file);
  130.         } catch (FileNotFoundException e) {
  131.             LOGGER.log(Level.FINE, "readFile", e);
  132.         } catch (IOException e) {
  133.             LOGGER.log(Level.WARNING, "readFile", e);
  134.         }
  135.         return null;
  136.     }

  137.     @SuppressWarnings("DefaultCharset")
  138.     public static void writeFileOrThrow(File file, CharSequence content) throws IOException {
  139.         FileWriter writer = new FileWriter(file, false);
  140.         try {
  141.             writer.write(content.toString());
  142.         } finally {
  143.             writer.close();
  144.         }
  145.     }

  146.     public static boolean writeFile(File file, CharSequence content) {
  147.         try {
  148.             writeFileOrThrow(file, content);
  149.             return true;
  150.         }
  151.         catch (IOException e) {
  152.             LOGGER.log(Level.WARNING, "writeFile", e);
  153.             return false;
  154.         }
  155.     }

  156.     public static FileOutputStream prepareFileOutputStream(File file) throws IOException {
  157.         if (!file.exists()) {

  158.             // Create parent directory
  159.             File parent = file.getParentFile();
  160.             if (!parent.exists() && !parent.mkdirs()) {
  161.                 throw new IOException("Cannot create directory " + parent.getAbsolutePath());
  162.             }

  163.             // Create file
  164.             if (!file.createNewFile()) {
  165.                 throw new IOException("Cannot create file " + file.getAbsolutePath());
  166.             }
  167.         }

  168.         if (file.isDirectory()) {
  169.             throw new AssertionError("File " + file.getAbsolutePath() + " is not a file!");
  170.         }

  171.         return new FileOutputStream(file);
  172.     }

  173.     public static FileInputStream prepareFileInputStream(File file) throws IOException {
  174.         if (file.exists()) {
  175.             if (file.isFile()) {
  176.                 return new FileInputStream(file);
  177.             } else {
  178.                 throw new IOException("File " + file.getAbsolutePath() + " is not a file!");
  179.             }
  180.         } else {
  181.             throw new FileNotFoundException("File " + file.getAbsolutePath() + " not found.");
  182.         }
  183.     }

  184.     public static void maybeDeleteFileOrThrow(File file) throws IOException {
  185.         if (!file.exists()) {
  186.             return;
  187.         }

  188.         boolean successfullyDeleted = file.delete();
  189.         if (!successfullyDeleted) {
  190.             throw new IOException("Could not delete file " + file);
  191.         }
  192.     }

  193.     public static void maybeCreateFileWithParentDirectories(File file) throws IOException {
  194.         File parent = file.getParentFile();
  195.         if (!parent.exists() && !parent.mkdirs()) {
  196.             throw new IOException("Cannot create directory " + parent);
  197.         }

  198.         if (file.isFile()) {
  199.             return;
  200.         }

  201.         if (!file.exists()) {
  202.             if (file.createNewFile()) {
  203.                 return;
  204.             }
  205.             throw new IOException("Cannot create file " + file);
  206.         }

  207.         if (file.isDirectory()) {
  208.             throw new IOException("File " + file + " exists, but is a directory.");
  209.         } else {
  210.             throw new IOException("File " + file + " exists, but is neither a file nor a directory");
  211.         }
  212.     }
  213. }