- First you need to read the file
- Second you need to know where you want to save the new file
- Third you need to copy or cut the file to the new location
- I like to use the apache lib, FileUtils is simple and easy to use
Below is a method I use to do this
public static File changeUploadedFileInFile(UploadedFile fileOld, String pathSaveFile) throws IOException
{
File file = new File(pathSaveFile);
OutputStream outputStream = null;
InputStream input = null;
try
{
FileUtils.forceMkdir(file);
file = new File(pathSaveFile + fileOld.getFileName());
outputStream = new FileOutputStream(file);
input = fileOld.getInputstream();
int read = 0;
byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) != -1)
{
outputStream.write(bytes, 0, read);
}
return file;
}catch (IOException e)
{
LOG.error(SysUtilLogLevel.ERROR, "Error close stream file importer", e);
throw new IOException();
}
finally
{
if (outputStream != null)
{
try
{
outputStream.close();
}
catch (IOException e)
{
LOG.error(MarkerFactory.getMarker("error"), "Error close stream file importer", e);
}
}
if (input != null)
{
try
{
input.close();
}
catch (IOException e)
{
LOG.error(MarkerFactory.getMarker("error"), "Error close stream file importer", e);
}
}
This method is creating a new file in pathSaveFile, and copying the old file into the new file. Do not delete the old file if it exists. but you do not even need to save can use Stream Direct from memory if the files are not too large.