101 lines
2.4 KiB
Java
101 lines
2.4 KiB
Java
package org.gcube.portlets.user.geoportaldataentry.server.config;
|
|
|
|
import java.io.ByteArrayInputStream;
|
|
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;
|
|
import java.nio.file.StandardCopyOption;
|
|
|
|
/**
|
|
* The Class FileUtil.
|
|
*
|
|
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
|
|
*
|
|
* Dec 2, 2021
|
|
*/
|
|
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();
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
* Input stream to temp file.
|
|
*
|
|
* @param copyString the copy string
|
|
* @return
|
|
* @throws IOException Signals that an I/O exception has occurred.
|
|
*/
|
|
public static File inputStreamToTempFile(String copyString, String prefixFile) throws IOException {
|
|
|
|
File targetFile = null;
|
|
try {
|
|
InputStream initialStream = new ByteArrayInputStream(copyString.getBytes());
|
|
targetFile = File.createTempFile(prefixFile, ".tmp");
|
|
|
|
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
|
|
|
try {
|
|
if (initialStream != null) {
|
|
initialStream.close();
|
|
}
|
|
} catch (IOException ioe) {
|
|
// ignore
|
|
}
|
|
return targetFile;
|
|
} finally {
|
|
try {
|
|
if (targetFile != null)
|
|
targetFile.deleteOnExit();
|
|
} catch (Exception e) {
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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);
|
|
}
|
|
|
|
}
|