com.adobe.platform.operation.internal.util.FileUtil Maven / Gradle / Ivy
The 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 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;
import java.io.*;
import java.nio.file.FileAlreadyExistsException;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
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 "";
}
}
public static ZipOutputStream addZipEntry(ZipOutputStream zipOutputStream, String fileName, InputStream inputStream)
throws IOException{
ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.putNextEntry(zipEntry);
IOUtils.copy(inputStream, zipOutputStream);
zipOutputStream.closeEntry();
return zipOutputStream;
}
public static ZipOutputStream addZipEntry(ZipOutputStream zipOutputStream, String fileName, byte[] byteData)
throws IOException{
ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(byteData, 0, byteData.length);
zipOutputStream.closeEntry();
return zipOutputStream;
}
}