geoportal-data-entry-app/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/config/FileUtil.java

69 lines
1.6 KiB
Java

package org.gcube.portlets.user.geoportaldataentry.server.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
// TODO: Auto-generated Javadoc
/**
* The Class FileUtil.
*
* @author Francesco Mangiacrapa at ISTI-CNR Pisa (Italy)
* Apr 21, 2020
*/
public class FileUtil {
/**
* Input stream to temp file.
*
* @param inputStream the input stream
* @param fileName the file name
* @return the file
* @throws IOException Signals that an I/O exception has occurred.
*/
// InputStream -> Temp File
public static File inputStreamToTempFile(InputStream inputStream, String fileName)
throws IOException {
File tempFile = File.createTempFile(fileName, ".tmp");
//File tempFile = File.createTempFile("MyAppName-", ".tmp");
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
return tempFile;
}finally {
tempFile.deleteOnExit();
}
}
/**
* Copy input stream to file.
*
* @param is the is
* @param to the to
* @return the file
* @throws IOException Signals that an I/O exception has occurred.
*/
public static File copyInputStreamToFile(InputStream is, String to) throws IOException {
Path dest = Paths.get(to);
Files.copy(is, dest);
return new File(to);
}
}