How to convert org.apache.myfaces.trinidad.model.UploadedFile to java.io.File in Java?

It’s pretty common to have to convert an org.apache.myfaces.trinidad.model.UploadedFile to a java.io.File when working with an ADF <af:inputFile>.

Working with a java.io.File being the only way to retrieve values from a CSV.

Here is a simple code snippet to do so :

public static File uploadedFileToFileConverter(UploadedFile uf) {
InputStream inputStream = null;
OutputStream outputStream = null;
//Add you expected file encoding here:
System.setProperty("file.encoding", "UTF-8");
File newFile = new File(uf.getFilename());
try {
inputStream = uf.getInputStream();
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
//Do something with the Exception (logging, etc.)
}
return newFile;
}


Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.