/src/main/java/com/corecanarias/agora/lib/FileUtil.java
Java | 330 lines | 200 code | 34 blank | 96 comment | 18 complexity | 8c0e69e8214e4a3322e6131879d3fad2 MD5 | raw file
- package com.corecanarias.agora.lib;
- import java.beans.PropertyChangeEvent;
- import java.beans.PropertyChangeListener;
- import java.io.File;
- import java.io.FileFilter;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FilenameFilter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.math.BigInteger;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.util.List;
- import org.apache.commons.lang.StringUtils;
- import org.mozilla.universalchardet.UniversalDetector;
- /**
- * Utils for file and directory management
- *
- * @author ieb@corecanarias.com
- *
- */
- public class FileUtil {
- /**
- * Create a temp directory so-aware
- * @param prefix
- * @param sufix
- * @return
- */
- public static final File createTempDir(String prefix, String sufix) {
-
- File tempDir;
- try {
- tempDir = File.createTempFile(prefix, sufix);
- tempDir.delete();
- tempDir.mkdir();
- return tempDir;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public static final boolean equals(File f1, File f2) {
- if(f1 == f2) {
- return true;
- }
- if(f1 == null || f2 == null) {
- return false;
- }
- return f1.getAbsolutePath().equals(f2.getAbsolutePath());
- }
-
- /**
- * Delete a directory and all its content
- * @param path Directory to delete
- */
- public static final void deleteDir(File path) {
-
- if (path.exists()) {
- File[] files = path.listFiles();
-
- for (int i = 0; i < files.length; i++) {
- if (files[i].isDirectory()) {
- deleteDir(files[i]);
- files[i].delete();
- } else {
- files[i].delete();
- }
- }
- path.delete();
- }
- }
-
- /**
- * Delete a single file
- * @param file The absolute path to the file
- */
- public static final void deleteFile(String file) {
-
- deleteFile(new File(file));
- }
- /**
- * Delete a single file
- *
- * @param file The File object pointing to the file
- */
- public static final void deleteFile(File file) {
- file.delete();
- }
- public static final String getCharset(File file) throws IOException {
- FileInputStream fis = new FileInputStream(file);
-
- UniversalDetector detector = new UniversalDetector(null);
-
- byte[] buf = new byte[4096];
- int nread;
- while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
- detector.handleData(buf, 0, nread);
- }
- detector.dataEnd();
- fis.close();
- return detector.getDetectedCharset();
- }
-
- /**
- * Copy a InputStream into another and notify the process of the copy. You are encourged to open and close the streams.
- * Also you can cancel the copy by setting the propagationId of any PROGRESS PropertyChangeEvent to CANCEL
- *
- * @param in Source stream
- * @param out Dest stream
- * @param progress Listener to get the progress notifications
- * @return True if it was sucessfully copied false if it was cancelled by the user
- * @throws IOException In case of read/write problems
- */
- public static final boolean copyInputStream(InputStream in, OutputStream out, PropertyChangeListener progress) throws IOException {
- byte[] buffer = new byte[1024];
- int len;
- long count = 0;
- while ((len = in.read(buffer)) >= 0) {
- count += len;
- if(progress != null) {
- PropertyChangeEvent evt = new PropertyChangeEvent(progress, "PROGRESS", len, count);
- progress.propertyChange(evt);
- if(StringUtils.equals((String)evt.getPropagationId(), "CANCEL")) {
- return false;
- }
- }
- out.write(buffer, 0, len);
- }
- return true;
- }
-
- /**
- * Copy a file to another and notify the process of the copy. Also you can cancel the copy by setting
- * the propagationId of any PROGRESS PropertyChangeEvent to CANCEL
- *
- * @param orig The absolute path to orig file
- * @param dest The absolute path to dest file
- * @param progress Listener to get the progress notifications
- * @return True it was sucessfully copied, false in another case.
- */
- public static final boolean copyFiles(String orig, String dest, PropertyChangeListener progress) {
-
- try {
- FileInputStream forig = new FileInputStream(orig);
- FileOutputStream fdest = new FileOutputStream(dest);
- FileUtil.copyInputStream(forig, fdest, progress);
- } catch (FileNotFoundException e) {
- return false;
- } catch (IOException e) {
- return false;
- }
- return true;
- }
-
- /**
- * Check if two files are equals.
- *
- * This method use md5 to the comparasion
- * @param fname1
- * @param fname2
- * @return
- * @throws NoSuchAlgorithmException
- * @throws IOException
- */
- public static boolean isSameFile(String fname1, String fname2) throws NoSuchAlgorithmException, IOException {
-
- return StringUtils.equals(md5File(new File(fname1)), md5File(new File(fname2)));
- }
- /**
- * Test if any file with a name starting with the name of filename exists in the directory
- *
- * @param dir The directory where to lookup
- * @param filename The absolute path where extract the name of the file
- * @return True if exists a file with a name starting with the filename name, false in another case.
- */
- public static final boolean filenameExists(String dir, String filename) {
- final String fname = new File(filename).getName();
- String[] res = new File(dir).list(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return StringUtils.startsWith(name, fname);
- }
-
- });
- return res.length > 0;
- }
- /**
- * Test if any file with a name starting with the name of filename exists in the directory. No taking in account the extenions
- * of the file.
- *
- * @param dir The directory where to lookup
- * @param filename The absolute path where extract the name of the file
- * @return True if exists a file with a name starting with the filename name, false in another case.
- */
- public static final boolean filenameNoExtensionExists(String dir, String filename) {
- final String fname = new File(filename).getName();
- String[] res = new File(dir).list(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- String[] parts = FileUtil.splitFilename(fname);
- return StringUtils.startsWith(name, parts[0]);
- }
-
- });
- return res.length > 0;
- }
-
- /**
- * Separate the filename itself and the extension of a filename
- * @param filename The name of the file
- * @return An array with two position the first one is the filename and the second one is the extension
- */
- public static final String[] splitFilename(String filename) {
-
- String[] res = new String[2];
- int idx = filename.lastIndexOf(".");
- res[0] = filename.substring(0, idx);
- res[1] = filename.substring(idx);
- return res;
- }
-
- /**
- * MD5 of a stream
- *
- * @param file The file
- * @return An string representing the MD5 sum.
- * @throws IOException
- * @throws NoSuchAlgorithmException
- */
- public static final String md5(InputStream stream) throws IOException, NoSuchAlgorithmException {
-
- MessageDigest m = MessageDigest.getInstance("MD5");
- byte[] buffer = new byte[1024];
- int len;
- long count = 0;
- while((len = stream.read(buffer)) >= 0) {
- count += len;
- m.update(buffer, 0, len);
- }
- BigInteger i = new BigInteger(1, m.digest());
- if(stream.markSupported()) {
- stream.reset();
- }
- return String.format("%1$032x", i);
- }
-
- /**
- * MD5 of a file
- *
- * @param file The file
- * @return An string representing the MD5 sum.
- * @throws IOException
- * @throws NoSuchAlgorithmException
- */
- public static final String md5File(File file) throws IOException, NoSuchAlgorithmException {
- FileInputStream forig = new FileInputStream(file);
- return md5(forig);
- }
- /**
- * Check in linux system if a file is a symbolic link.
- * @param f The file to test
- *
- * @return True if it's a symbolic link false otherwise
- */
- public static final boolean isLinuxSymLink(File f) {
-
- if("\\".equals(File.separator)) {
- return false;
- }
-
- try {
- File canonicalFile;
- if (f.getParent() == null) {
- canonicalFile = f;
- } else {
- File canonicalDir = f.getParentFile().getCanonicalFile();
- canonicalFile = new File(canonicalDir, f.getName());
- }
- return !canonicalFile.getCanonicalFile().equals(canonicalFile.getAbsoluteFile());
- } catch(IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Lookup for files/directories inside of a root directory recursively.
- *
- * The difference with Apache FileUtils is that this method can find directories too
- * not only files like the FileUtils in commons-io
- *
- * @param result An initialized list where it will put the Files found
- * @param root The root directory where to search
- * @param filter The filter applied in the search
- *
- * @See org.apache.commons.io.FileUtils
- */
- public static final void listDirectories(List<File> result, File root, FileFilter filter) {
- File[] dirs = root.listFiles(new FileFilter() {
- @Override
- public boolean accept(File file) {
- return file.isDirectory() && !FileUtil.isLinuxSymLink(file);
- }
- });
- if(dirs != null) {
- for(File d: dirs) {
- if(filter == null || filter.accept(d)) {
- result.add(d);
- }
- listDirectories(result, d, filter);
- }
- }
- }
- }