Sunday, November 9, 2014

File Utilities - Java


The below class holds methods that can be used to perform most of the routine actions on files and folders. Feel free to use the code anywhere required.

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Utility class that holds all methods related to File handling
 *
 * @author Sridhar
 */
public class FileUtility {

    /**
     * Deletes a given directory under the current working folder. If the
     * directory is in a sub folder, the path relative to the current folder
     * needs to be given. All subfolders and files under this directory will be
     * deleted.
     *
     * @param directoryName The directory along with the path relative to the
     * current directory.
     * @return boolean true if deleted successfully
     * @throws java.io.IOException
     */
    public static boolean deleteDirectory(String directoryName) throws IOException {
        File file = new File(directoryName);
        return deleteDirectory(file);
    }

    /**
     * Overridden method with the parameter changed to File.
     *
     * @param path The File object of the directory.
     * @return boolean true if deleted successfully
     */
    public static boolean deleteDirectory(File path) {
        boolean success = true;
        if (path.exists()) {
            File[] files = path.listFiles();
            for (File file : files) {
                if (success) {
                    if (file.isDirectory()) {
                        success = deleteDirectory(file);
                    } else {
                        success = file.delete();
                    }
                }
            }
        }
        return (path.delete());
    }

    /**
     * deletes a file given by the input String
     *
     * @param fileName The filename along with the path relative to the current
     * directory.
     * @return boolean true if deleted successfully
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        boolean success = file.delete();
        return success;
    }

    /**
     * creates a directory as given by the input String
     *
     * @param location The directory along with the path relative to the current
     * directory.
     * @return boolean true if created successfully
     */
    public static boolean createDirectory(String location) {
        File file = new File(location);
        boolean success = file.mkdirs();
        return success;
    }

    /**
     * removes the file extension from a given file name and returns the rest of
     * the name.
     *
     * @param str input file name along with extension of the file.
     * @return String file name without the extension.
     */
    public static String stripExtension(String str) {
        if (str == null) {
            return null;
        }
        int pos = str.lastIndexOf(".");
        if (pos == -1) {
            return str;
        }
        return str.substring(0, pos);
    }

    /**
     * Retrieves the file extension
     *
     * @param str input file name along with extension of the file.
     * @return String file name without the extension.
     */
    public static String getFileExtension(String str) {
        if (str == null) {
            return null;
        }
        int pos = str.lastIndexOf(".");
        if (pos == -1) {
            return str;
        }
        return str.substring(pos, str.length());
    }

    /**
     * Checks if a given file exists in the file system.
     *
     * @param fileString The file along with the path relative to the current
     * directory.
     * @return boolean true if found else, returns false.
     */
    public static boolean fileExists(String fileString) {
        File file = new File(fileString);
        return file.exists();
    }

    /**
     * Writes the given message to the input file. Also closes the file at the
     * end of it.
     *
     * @param fle A file object where the message needs to be written to.
     * @param message the content to be written to the file.
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public static void writeToFile(File fle, String message)
            throws FileNotFoundException, IOException {
        FileOutputStream fos;
        fos = new FileOutputStream(fle, true);
        fos.write(message.getBytes());
        fos.write(("\n").getBytes());
        fos.flush();
        fos.close();
    }

    /**
     *
     * @param fileName name of the file to be created
     * @param fileContent content to be written to the created file.
     * @return File. a reference to the file object created
     * @throws java.io.IOException
     */
    public static File createFile(String fileName, String fileContent) throws IOException {
        FileWriter fstream = null;
        File file = null;
        try {
            file = new File(fileName);
            fstream = new FileWriter(file);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(fileContent);
            out.flush();
            out.close();
        } catch (IOException ex) {
            return null;
        } finally {
            if (fstream != null) {
                fstream.close();
            }
        }
        return file;
    }

    /**
     * Starts a windows ".bat" file in a new command prompt. Works only when run
     * on Windows.
     *
     * @param runnableFile path to the runnable file.
     * @param folderName
     * @throws java.io.IOException
     */
    public static void runWindowsFile(String runnableFile, String folderName) throws IOException {
        File file = new File(FileUtility.stripExtension(folderName));
        String filePath = runnableFile;
        Map<String, String> env = new HashMap<String, String>(System.getenv());
        env.put("Path", env.get("Path") + ";" + file.getAbsolutePath());
        Runtime.getRuntime().exec("cmd /c start " + filePath);

    }

    /**
     * Starts a ".sh" file in a terminal. Works only when run on Linux based
     * Operating systems.
     *
     * @param runnableFile - path to the runnableFile
     * @throws java.io.IOException
     */
    public static void runShellScript(String runnableFile) throws IOException {
        Runtime.getRuntime().exec(runnableFile);
    }

    /**
     * Reads contents of a text file.
     *
     * @param fileNameWithPath - Path to the file
     * @return String - Content of the file.
     * @throws IOException
     */
    public static String readFileContent(String fileNameWithPath) throws IOException {
        InputStream is = FileUtility.class.getClassLoader().getResourceAsStream(fileNameWithPath);
        return readContentFromInputStream(is);
    }

    public static String readContentFromInputStream(InputStream is) throws IOException {
        if (is != null) {
            StringBuilder stringBuilder = new StringBuilder();
            BufferedInputStream stream = new BufferedInputStream(is);
            byte[] contents = new byte[1024];
            int bytesRead;
            while ((bytesRead = stream.read(contents)) != -1) {
                stringBuilder.append(new String(contents, 0, bytesRead));
            }
            stream.close();
            is.close();
            return stringBuilder.toString();
        }
        return null;
    }

    public static String readFileContent(File file) throws IOException {
        return readContentFromInputStream(new FileInputStream(file));
    }

    public static String getFileFolder(String absolutePath) {
        if (StringUtility.isNullOrEmpty(absolutePath)) {
            return null;
        } else if (absolutePath.indexOf(File.separator) <= 0) {
            return absolutePath;
        }
        return absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
    }

    public static String[] getFilesInFolder(String absolutePath) {
        if (!StringUtility.isNullOrEmpty(absolutePath)) {
            File file = new File(absolutePath);
            ArrayList<String> filesList = new ArrayList<String>();
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File fl : files) {
                    if (fl.isFile()) {
                        double bytes = fl.length();
                        double kilobytes = (bytes / 1024);
                        double megabytes = (kilobytes / 1024);
                        filesList.add(fl.getName() + "," + megabytes + "");
                    }
                }
                return filesList.toArray(new String[filesList.size()]);
            } else {
                return null;
            }
        }
        return null;
    }

}




No comments:

Post a Comment