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

com.adobe.platform.operation.internal.util.FileUtil Maven / Gradle / Ivy

There is a newer version: 1.3.1
Show newest version
/*
 * Copyright 2019 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it. If you have received this file from a source other than Adobe,
 * then your use, modification, or distribution of it requires the prior
 * written permission of Adobe.
 */

package com.adobe.platform.operation.internal.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileAlreadyExistsException;
import java.util.UUID;

import org.apache.commons.io.FileExistsException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    public static void moveFile(String source, String destination) throws IOException {
        try {
            FileUtils.moveFile(new File(source), new File(destination));
        } catch (FileExistsException f) {
            LOGGER.error("File at location {} already exists", destination);
            throw new FileAlreadyExistsException(destination);
        }
    }


    public static void moveFileToStream(String filePath, OutputStream targetStream) throws IOException {
        LOGGER.debug("Moving file at {} to provided OutputStream", filePath);
        File operationResultFile = new File(filePath);
        try (FileInputStream fileInputStream = new FileInputStream(operationResultFile)) {
            IOUtils.copy(fileInputStream, targetStream);
            // Delete the file only if the copying is successful, not inside finally
            if (operationResultFile.delete()) {
                LOGGER.debug("Temporary file at {} deleted successfully", filePath);
            }
        }
    }


    /**
     * Returns a random file name with the extension provided
     *
     * @param extension extension with which the file name will be generated
     * @return
     */
    public static String getRandomFileName(String extension) {
        if (extension != null) {
            if (extension.startsWith(".")) {
                return UUID.randomUUID().toString().replace("-", "") + extension;
            } else {
                return UUID.randomUUID().toString().replace("-", "") + "." + extension;
            }
        } else {
            return "";
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy