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

src.main.java.com.vincomobile.fw.basic.tools.FileTool Maven / Gradle / Ivy

There is a newer version: 5.1.0-RELEASE
Show newest version
package com.vincomobile.fw.basic.tools;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileTool {

    private static Logger logger = LoggerFactory.getLogger(FileTool.class);

    public static String dir = "";
    public static String dateInfo = "";

    /**
     * Get file extension
     *
     * @param file File
     * @return File extension
     */
    public static String getFileExt(File file) {
        int dotPos = file.getName().lastIndexOf(".");
        return file.getName().substring(dotPos);
    }

    public static String getFileExt(String fName) {
        int dotPos = fName.lastIndexOf(".");
        return fName.substring(dotPos);
    }

    /**
     * Get unique name for a file
     *
     * @param prefix Prefix
     * @param ext    Extension
     * @return Unique file name
     */
    public static String getFileName(String prefix, String ext) {
        String fname = dir + "/" + prefix + dateInfo;
        File file = new File(fname + "_1" + ext);
        for (int i = 2; file.exists(); i++)
            file = new File(fname + "_" + i + ext);
        return file.getName();
    }

    /**
     * Update current day
     */
    public static void setDateInfo() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        dateInfo = df.format(new Date());
    }

    /**
     * Check if exists the PATH and create if not exists
     *
     * @param path PATH to verifiy
     * @return true if successful
     */
    public static boolean buildPath(String path) {
        File dir = new File(path);
        return dir.isDirectory() || dir.mkdirs();
    }

    /**
     * Remove directory content
     *
     * @param path Directory
     * @return Success or Fail
     */
    public static boolean deleteDirContent(String path) {
        boolean result = true;
        File f = new File(path);
        String files[] = f.list();
        if (files != null) {
            for (String file : files) {
                File f2 = new File(path + "/" + file);
                if (f2.isDirectory())
                    result = deleteDirContent(path + "/" + file);
                if (result)
                    result = f2.delete();
                if (!result)
                    return false;
            }
        }
        return true;
    }

    /**
     * Remove directory content and directory
     *
     * @param path Directory
     * @return Success or Fail
     */
    public static boolean deleteDir(String path) {
        boolean result = deleteDirContent(path);
        if (result) {
            result = deleteFile(path);
        }
        return result;
    }

    /**
     * Remove a file
     *
     * @param path File name
     * @return Success or Fail
     */
    public static boolean deleteFile(String path) {
        return deleteFile(new File(path));
    }

    public static boolean deleteFile(File f) {
        return !f.exists() || f.delete();
    }

    /**
     * Copy a directory content
     *
     * @param sourceDir Source directory
     * @param destDir Destination directory
     * @param prefix File prefix
     */
    public static boolean copyDirectory(File sourceDir, File destDir, String prefix) {
        if (sourceDir.exists() && sourceDir.isDirectory()) {
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            File[] sourcesFiles = sourceDir.listFiles();
            for (File sourceFile : sourcesFiles) {
                try {
                    if (sourceFile.isDirectory()) {
                        if (!copyDirectory(sourceFile, new File(destDir + "/" + sourceFile.getName()), prefix))
                            return false;
                    } else {
                        FileUtils.copyFile(sourceFile, new File(destDir + "/" + (prefix != null ? prefix : "") + sourceFile.getName()));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean copyDirectory(File sourceDir, File destDir) {
        return copyDirectory(sourceDir, destDir, null);
    }

    /**
     * Clean file name
     *
     * @param fileName File name
     * @return Clean name
     */
    public static String cleanFileName(String fileName) {
        // Se convierten los acentuados a normales
        fileName = Converter.getRemoveTilde(fileName);
        // Se eliminan todos los que no son validos
        fileName = fileName.replaceAll("\\(", "-");
        fileName = fileName.replaceAll("\\)", "-");
        fileName = fileName.replaceAll("[^a-zA-Z0-9-\\.-_]", "_");
        fileName = fileName.replaceAll("\\?", "_");
        fileName = fileName.replaceAll("\\^", "_");
        fileName = fileName.replaceAll("\\[", "_");
        // Se eliminan los __ repetidos
        while (fileName.contains("..")) {
            fileName = fileName.replaceAll("\\.\\.", ".");
        }
        while (fileName.contains("__")) {
            fileName = fileName.replaceAll("__", "_");
        }
        while (fileName.contains("--")) {
            fileName = fileName.replaceAll("--", "-");
        }
        // Minusculas
        fileName = fileName.toLowerCase();
        return fileName;
    }

    /**
     * Check file ContentType
     *
     * @param source File from navegator
     * @param contentType Valid content type
     * @return Success or fail
     */
    public static boolean validContentType(MultipartFile source, String contentType) {
        if (!Converter.isEmpty(contentType)) {
            String[] contents = contentType.split(";");
            for (String content : contents) {
                if (content.equals(source.getContentType()))
                    return true;
            }
            return false;
        }
        return true;
    }

    /**
     * Check max size for file
     *
     * @param source File from navegator
     * @param maxSize Max size (KB)
     * @return Success or fail
     */
    public static boolean validSize(MultipartFile source, Long maxSize) {
        return Converter.isEmpty(maxSize) || maxSize <= 0 || source.getSize() / 1024 <= maxSize;
    }

    /**
     * Save file
     *
     * @param source File from navegator
     * @param fileName Destination file name
     * @param autoUnzip Auto unzip file
     * @param deleteZip Remove zip file
     * @return Success or fail
     */
    public static File saveFile(MultipartFile source, String fileName, boolean autoUnzip, boolean deleteZip) {
        OutputStream out = null;
        try {
            // Build directory structure
            File file = new File(fileName);
            File dir = new File(file.getParent());
            if (!dir.exists())
                dir.mkdirs();

            // Save file
            out = new FileOutputStream(file);
            IOUtils.copy(source.getInputStream(), out);

            // Auto un zip
            if (autoUnzip && source.getContentType().endsWith("zip")) {
                UnZipManager zipManager = new UnZipManager(file.getPath());
                fileName = file.getName();
                int idx = fileName.lastIndexOf('.');
                fileName = idx > 0 ? fileName.substring(0, idx) : "_" + fileName;
                File zipDir = zipManager.extractFilesFromZipFile(file.getParent() + File.separator + fileName);
                if (deleteZip)
                    file.delete();
                return zipDir;
            } else {
                return file;
            }
        } catch (Exception e) {
            logger.error("Error saving file: " + fileName);
            logger.error(e.getMessage());
            return null;
        }
    }

    public static File saveFile(MultipartFile source, String fileName, boolean autoUnzip) {
        return saveFile(source, fileName, autoUnzip, true);
    }

    public static File saveFile(MultipartFile source, String fileName) {
        return saveFile(source, fileName, false, false);
    }

    /**
     * Load a text file
     *
     * @param source Text file
     * @param removeDuplicate Remove duplicate lines
     * @return Lines
     */
    public static List readTxtFile(File source, boolean removeDuplicate) {
        try {
            List result = new ArrayList<>();
            FileReader fileReader = new FileReader(source);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (!Converter.isEmpty(line)) {
                    if (removeDuplicate) {
                        if (!result.contains(line))
                            result.add(line);
                    } else {
                        result.add(line);
                    }
                }
            }
            fileReader.close();
            return result;
        } catch (IOException e) {
            logger.error("Error reading file: " + source.getAbsolutePath());
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * Write to text file
     *
     * @param dest Destination file
     * @param lines Text lines
     * @return Success or failure
     */
    public static boolean writeTxtFile(File dest, List lines) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(dest));
            for (String line : lines) {
                writer.write(line + "\n");
            }
            writer.close();
            return true;
        } catch (Exception e) {
            logger.error("Error writing file: " + dest.getAbsolutePath());
            logger.error(e.getMessage());
            return false;
        }
    }

    /**
     * Get file from Multipart file
     *
     * @param multipart Multipart file
     * @return File
     */
    public static File multipartToFile(MultipartFile multipart) {
        try {
            File convFile = File.createTempFile(multipart.getOriginalFilename(), null);
            multipart.transferTo(convFile);
            return convFile;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return null;
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy