Version 4.4.5
[nikiroo-utils.git] / src / be / nikiroo / utils / IOUtils.java
index 3516fd20af2155ee7f54483c3bc7b2ba877371ed..e9a378c0fd6e279c1568afb848808ab83f9cdf5e 100644 (file)
@@ -1,20 +1,23 @@
 package be.nikiroo.utils;
 
 import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
-import java.io.FileReader;
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.InputStreamReader;
 import java.io.OutputStream;
-import java.util.stream.Stream;
+import java.util.ArrayList;
+import java.util.List;
 import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
 import java.util.zip.ZipOutputStream;
 
 /**
- * This class offer some utilities based around {@link Stream}s.
+ * This class offer some utilities based around Streams and Files.
  * 
  * @author niki
  */
@@ -44,7 +47,7 @@ public class IOUtils {
         * 
         * @param in
         *            the data source
-        * @param target
+        * @param out
         *            the target {@link OutputStream}
         * 
         * @throws IOException
@@ -87,8 +90,12 @@ public class IOUtils {
                                }
                                zip.putNextEntry(new ZipEntry(base + "/"));
                        }
-                       for (File file : target.listFiles()) {
-                               zip(zip, base, file, false);
+
+                       File[] files = target.listFiles();
+                       if (files != null) {
+                               for (File file : files) {
+                                       zip(zip, base, file, false);
+                               }
                        }
                } else {
                        if (base == null || base.isEmpty()) {
@@ -113,7 +120,7 @@ public class IOUtils {
         *            the source {@link File} (which can be a directory)
         * @param dest
         *            the destination <tt>.zip</tt> file
-        * @param srctIsRoot
+        * @param srcIsRoot
         *            FALSE if we need to add a {@link ZipEntry} for src, TRUE to
         *            add it at the root of the ZIP
         * 
@@ -135,6 +142,58 @@ public class IOUtils {
                }
        }
 
+       /**
+        * Unzip the given ZIP file into the target directory.
+        * 
+        * @param zipFile
+        *            the ZIP file
+        * @param targetDirectory
+        *            the target directory
+        * 
+        * @return the number of extracted files (not directories)
+        * 
+        * @throws IOException
+        *             in case of I/O errors
+        */
+       public static long unzip(File zipFile, File targetDirectory)
+                       throws IOException {
+               long count = 0;
+
+               if (targetDirectory.exists() && targetDirectory.isFile()) {
+                       throw new IOException("Cannot unzip " + zipFile + " into "
+                                       + targetDirectory + ": it is not a directory");
+               }
+
+               targetDirectory.mkdir();
+               if (!targetDirectory.exists()) {
+                       throw new IOException("Cannot create target directory "
+                                       + targetDirectory);
+               }
+
+               FileInputStream in = new FileInputStream(zipFile);
+               try {
+                       ZipInputStream zipStream = new ZipInputStream(in);
+                       try {
+                               for (ZipEntry entry = zipStream.getNextEntry(); entry != null; entry = zipStream
+                                               .getNextEntry()) {
+                                       File file = new File(targetDirectory, entry.getName());
+                                       if (entry.isDirectory()) {
+                                               file.mkdirs();
+                                       } else {
+                                               IOUtils.write(zipStream, file);
+                                               count++;
+                                       }
+                               }
+                       } finally {
+                               zipStream.close();
+                       }
+               } finally {
+                       in.close();
+               }
+
+               return count;
+       }
+
        /**
         * Write the {@link String} content to {@link File}.
         * 
@@ -154,7 +213,23 @@ public class IOUtils {
                        dir.mkdirs();
                }
 
-               FileWriter writerVersion = new FileWriter(new File(dir, filename));
+               writeSmallFile(new File(dir, filename), content);
+       }
+
+       /**
+        * Write the {@link String} content to {@link File}.
+        * 
+        * @param file
+        *            the {@link File} to write
+        * @param content
+        *            the content
+        * 
+        * @throws IOException
+        *             in case of I/O error
+        */
+       public static void writeSmallFile(File file, String content)
+                       throws IOException {
+               FileWriter writerVersion = new FileWriter(file);
                try {
                        writerVersion.write(content);
                } finally {
@@ -174,17 +249,74 @@ public class IOUtils {
         *             in case of I/O error
         */
        public static String readSmallFile(File file) throws IOException {
-               BufferedReader reader = new BufferedReader(new FileReader(file));
+               InputStream stream = new FileInputStream(file);
                try {
-                       StringBuilder builder = new StringBuilder();
-                       for (String line = reader.readLine(); line != null; line = reader
-                                       .readLine()) {
-                               builder.append(line);
-                       }
-                       return builder.toString();
+                       return readSmallStream(stream);
                } finally {
-                       reader.close();
+                       stream.close();
+               }
+       }
+
+       /**
+        * Read the whole {@link InputStream} content into a {@link String}.
+        * 
+        * @param stream
+        *            the {@link InputStream}
+        * 
+        * @return the content
+        * 
+        * @throws IOException
+        *             in case of I/O error
+        */
+       public static String readSmallStream(InputStream stream) throws IOException {
+               // do NOT close the reader, or the related stream will be closed, too
+               // reader.close();
+               BufferedReader reader = new BufferedReader(
+                               new InputStreamReader(stream));
+
+               StringBuilder builder = new StringBuilder();
+               for (String line = reader.readLine(); line != null; line = reader
+                               .readLine()) {
+                       builder.append(line);
+                       builder.append("\n");
+               }
+
+               return builder.toString();
+       }
+
+       /**
+        * Recursively delete the given {@link File}, which may of course also be a
+        * directory.
+        * <p>
+        * Will either silently continue or throw an exception in case of error,
+        * depending upon the parameters.
+        * 
+        * @param target
+        *            the target to delete
+        * @param exception
+        *            TRUE to throw an {@link IOException} in case of error, FALSE
+        *            to silently continue
+        * 
+        * @return TRUE if all files were deleted, FALSE if an error occurred
+        * 
+        * @throws IOException
+        *             if an error occurred and the parameters allow an exception to
+        *             be thrown
+        */
+       public static boolean deltree(File target, boolean exception)
+                       throws IOException {
+               List<File> list = deltree(target, null);
+               if (exception && !list.isEmpty()) {
+                       StringBuilder slist = new StringBuilder();
+                       for (File file : list) {
+                               slist.append("\n").append(file.getPath());
+                       }
+
+                       throw new IOException("Cannot delete all the files from: <" //
+                                       + target + ">:" + slist.toString());
                }
+
+               return list.isEmpty();
        }
 
        /**
@@ -195,22 +327,145 @@ public class IOUtils {
         * 
         * @param target
         *            the target to delete
+        * 
+        * @return TRUE if all files were deleted, FALSE if an error occurred
         */
-       public static void deltree(File target) {
-               for (File file : target.listFiles()) {
-                       if (file.isDirectory()) {
-                               deltree(file);
-                       } else {
-                               if (!file.delete()) {
-                                       System.err.println("Cannot delete file: "
-                                                       + file.getAbsolutePath());
-                               }
+       public static boolean deltree(File target) {
+               return deltree(target, null).isEmpty();
+       }
+
+       /**
+        * Recursively delete the given {@link File}, which may of course also be a
+        * directory.
+        * <p>
+        * Will collect all {@link File} that cannot be deleted in the given
+        * accumulator.
+        * 
+        * @param target
+        *            the target to delete
+        * @param errorAcc
+        *            the accumulator to use for errors, or NULL to create a new one
+        * 
+        * @return the errors accumulator
+        */
+       public static List<File> deltree(File target, List<File> errorAcc) {
+               if (errorAcc == null) {
+                       errorAcc = new ArrayList<File>();
+               }
+
+               File[] files = target.listFiles();
+               if (files != null) {
+                       for (File file : files) {
+                               errorAcc = deltree(file, errorAcc);
                        }
                }
 
                if (!target.delete()) {
-                       System.err.println("Cannot delete file: "
-                                       + target.getAbsolutePath());
+                       errorAcc.add(target);
+               }
+
+               return errorAcc;
+       }
+
+       /**
+        * Open the given /-separated resource (from the binary root).
+        * 
+        * @param name
+        *            the resource name
+        * 
+        * @return the opened resource if found, NLL if not
+        */
+       public static InputStream openResource(String name) {
+               ClassLoader loader = IOUtils.class.getClassLoader();
+               if (loader == null) {
+                       loader = ClassLoader.getSystemClassLoader();
+               }
+
+               return loader.getResourceAsStream(name);
+       }
+
+       /**
+        * Return a resetable {@link InputStream} from this stream, and reset it.
+        * 
+        * @param in
+        *            the input stream
+        * @return the resetable stream, which <b>may</b> be the same
+        * 
+        * @throws IOException
+        *             in case of I/O error
+        */
+       public static InputStream forceResetableStream(InputStream in)
+                       throws IOException {
+               MarkableFileInputStream tmpIn = null;
+               File tmp = null;
+
+               boolean resetable = in.markSupported();
+               if (resetable) {
+                       try {
+                               in.reset();
+                       } catch (IOException e) {
+                               resetable = false;
+                       }
+               }
+
+               if (resetable) {
+                       return in;
+               }
+
+               tmp = File.createTempFile(".tmp-stream", ".tmp");
+               try {
+                       write(in, tmp);
+                       tmpIn = new MarkableFileInputStream(new FileInputStream(tmp));
+                       return tmpIn;
+               } finally {
+                       try {
+                               if (tmpIn != null) {
+                                       tmpIn.close();
+                               }
+                       } finally {
+                               tmp.delete();
+                       }
+               }
+       }
+
+       /**
+        * Convert the {@link InputStream} into a byte array.
+        * 
+        * @param in
+        *            the input stream
+        * 
+        * @return the array
+        * 
+        * @throws IOException
+        *             in case of I/O error
+        */
+       public static byte[] toByteArray(InputStream in) throws IOException {
+               ByteArrayOutputStream out = new ByteArrayOutputStream();
+               write(in, out);
+
+               byte[] array = out.toByteArray();
+               out.close();
+
+               return array;
+       }
+
+       /**
+        * Convert the {@link File} into a byte array.
+        * 
+        * @param file
+        *            the input {@link File}
+        * 
+        * @return the array
+        * 
+        * @throws IOException
+        *             in case of I/O error
+        */
+       public static byte[] toByteArray(File file) throws IOException {
+               FileInputStream fis = new FileInputStream(file);
+               try {
+                       return toByteArray(fis);
+               } finally {
+                       fis.close();
                }
        }
 }