All Downloads are FREE. Search and download functionalities are using the official Maven repository.

edu.uvm.ccts.common.util.FileUtil Maven / Gradle / Ivy

Go to download

A library of useful generic objects and tools consolidated here to simplify all UVM CCTS projects

There is a newer version: 1.1.5
Show newest version
/*
 * Copyright 2015 The University of Vermont and State
 * Agricultural College.  All rights reserved.
 *
 * Written by Matthew B. Storer 
 *
 * This file is part of CCTS Common.
 *
 * CCTS Common is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CCTS Common is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with CCTS Common.  If not, see .
 */

package edu.uvm.ccts.common.util;

import edu.uvm.ccts.common.model.FileMetadata;
import edu.uvm.ccts.common.ui.JApproveFileChooser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by mstorer on 11/26/13.
 */
public class FileUtil {
    public static String buildPath(String ... parts) {
        if (parts.length == 0) {
            return ".";

        } else {
            String path = parts.length == 1 ?
                    parts[0] :
                    StringUtils.join(parts, File.separatorChar).replaceAll(File.separator + "{2,}", File.separator);

            return path.endsWith(File.separator) ?
                    path.substring(0, path.length() - 1) :
                    path;
        }
    }

    public static File selectFileToOpen(Component parent, javax.swing.filechooser.FileFilter filter, String currentDir) {
        JFileChooser fc = new JFileChooser();

        if (filter != null)     fc.setFileFilter(filter);
        if (currentDir != null) fc.setCurrentDirectory(new File(currentDir));

        int rval = fc.showOpenDialog(parent);

        return rval == JFileChooser.APPROVE_OPTION ?
                fc.getSelectedFile() :
                null;
    }

    public static File selectFileToSave(Component parent, javax.swing.filechooser.FileFilter filter, String currentDir,
                                        String defaultFilename) {

        JFileChooser fc = new JApproveFileChooser();

        if (filter != null)             fc.setFileFilter(filter);
        if (currentDir != null)         fc.setCurrentDirectory(new File(currentDir));
        if (defaultFilename != null)    fc.setSelectedFile(new File(defaultFilename));

        int rval = fc.showSaveDialog(parent);

        return rval == JFileChooser.APPROVE_OPTION ?
                fc.getSelectedFile() :
                null;
    }

    public static String read(String filename) throws IOException {
        byte[] bytes = readBytes(filename);
        return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
    }

    public static List readLines(String filename) throws IOException {
        return FileUtils.readLines(new File(filename));
    }

    public static void serializeToFile(String filename, Object object) throws IOException {
        ObjectOutput out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));

        try {
            out.writeObject(object);

        } finally {
            out.close();
        }
    }

    public static Object deserializeFromFile(String filename) throws IOException, ClassNotFoundException {
        ObjectInput in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filename)));

        try {
            return in.readObject();

        } finally {
            in.close();
        }
    }

    public static void writeBytes(String filename, byte[] bytes) throws IOException {
        OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));

        try {
            IOUtils.write(bytes, out);

        } finally {
            out.close();
        }
    }

    public static byte[] readBytes(String filename) throws IOException {
        InputStream in = new BufferedInputStream(new FileInputStream(filename));

        try {
            return IOUtils.toByteArray(in);

        } finally {
            in.close();
        }
    }

    public static void write(String filename, String s, boolean append) throws IOException {
        createDirectory(getPathPart(filename));

        File file = new File(filename);
        synchronized(file.getCanonicalPath().intern()) {
            OutputStream output = new BufferedOutputStream(new FileOutputStream(file, append));

            try {
                output.write(s.getBytes());

            } finally {
                try { output.flush(); } catch (Exception e) {}
                try { output.close(); } catch (Exception e) {}
            }
        }
    }

    public static void append(String srcFilename, String destFilename) throws IOException {
        File destFile = new File(destFilename);
        synchronized(destFile.getCanonicalPath().intern()) {
            InputStream input = new BufferedInputStream(new FileInputStream(srcFilename));
            OutputStream output = new BufferedOutputStream(new FileOutputStream(destFile, true));

            try {
                byte[] buf = new byte[32768];
                int len;
                while ((len = input.read(buf)) > 0) {
                    output.write(buf, 0, len);
                }

            } finally {
                try { input.close(); } catch (Exception e) {}
                try { output.flush(); } catch (Exception e) {}
                try { output.close(); } catch (Exception e) {}
            }
        }
    }

    public static boolean exists(String filename) {
        return new File(filename).exists();
    }

    public static void createDirectory(String dirname) throws IOException {
        if (dirname != null && ! dirname.isEmpty()) {
            File dir = new File(dirname);
            synchronized(dir.getCanonicalPath().intern()) {
                if ( ! dir.isDirectory() ) {
                    if ( ! dir.mkdirs() ) {
                        throw new IOException("couldn't create local directory '" + dirname + "'");
                    }
                }
            }
        }
    }

    public static void removeDirectory(String dirname) throws IOException {
        if (dirname != null && ! dirname.isEmpty()) {
            File dir = new File(dirname);
            synchronized(dir.getCanonicalPath().intern()) {
                if (dir.isDirectory()) {
                    FileUtils.deleteDirectory(new File(dirname));
                }
            }
        }
    }

    public static String getPathPart(String filename) {
        int index = filename.lastIndexOf(File.separatorChar);
        return index >= 0 ? filename.substring(0, index) : "";
    }

    public static String getFilenamePart(String filename) {
        int index = filename.lastIndexOf(File.separatorChar);
        return index < filename.length() - 1 ? filename.substring(index + 1) : "";
    }

    public static List listFiles(String dirname) {
        return listFiles(dirname, null);
    }

    public static List listFiles(String dirname, FileFilter filter) {
        File dir = new File(dirname);
        List list = new ArrayList();

        if (dir.isDirectory()) {
            File[] files = filter != null ?
                    dir.listFiles(filter) :
                    dir.listFiles();

            if (files != null) {
                Collections.addAll(list, files);
            }
        }

        return list;
    }

    public static List listFilesWithMetadata(String dirname) throws IOException {
        return listFilesWithMetadata(dirname, null);
    }

    public static List listFilesWithMetadata(String dirname, FileFilter filter) throws IOException {
        File dir = new File(dirname);
        List list = new ArrayList();

        if (dir.isDirectory()) {
            File[] files = filter != null ?
                    dir.listFiles(filter) :
                    dir.listFiles();

            if (files != null) {
                for (File file : files) {
                    list.add(new FileMetadata(file.getCanonicalPath(), file.lastModified(), file.length()));
                }
            }
        }

        return list;
    }

    public static void delete(String filename) {
        try {
            File file = new File(filename);
            synchronized(file.getCanonicalPath().intern()) {
                if (file.exists()) file.delete();
            }

        } catch (IOException e) {
            // handle silently
        }
    }

    public static void moveFile(String src, String dest) throws IOException {
        FileUtils.moveFile(new File(src), new File(dest));
    }

    public static String convertToAbsolutePath(String path) {
        return path;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy