0

I have a managed bean. An HTML/JSF page sends a zipped file as a Part. I need to extract the contents from it, but to do that I need it to be File. Is it possible to cast the Part to File like as follows, and then treat it like a normal zip file?

Part xmlFile;

public void myMethod()
{
File zippedFile = (File) getXmlFile();
....
}

If not, how would I go about doing so? I've looked on online but there seems to be very little information.

user3007194
  • 111
  • 1
  • 8

1 Answers1

1

You can create a temporary file:

File aFile = File.createTempFile(PREFIX, SUFFIX);

And write the contents of your Part payload into that file:

try (InputStream input = part.getInputStream()) {
    Files.copy(input, aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

You may also want to make use of File's delete() or deleteOnExit() for cleaning up resources. Bear in mind that deleteOnExit() is only invoked when the JVM exits, which may not be what you want in your case.

ktorn
  • 1,032
  • 8
  • 14
  • Thanks. So if the file was a .zip before becoming a Part, I will have the same .zip again when I create a file from inputstream? – user3007194 May 07 '15 at 04:21
  • You will end-up with the exact same contents of the original .zip file. – ktorn May 07 '15 at 04:31
  • File.createTempFile(PREFIX, SUFFIX); creates a file on disk. @user3007194, what is final destination of Part - disk, database, post processing, other? – Grady G Cooper May 07 '15 at 04:48
  • @GradyGCooper is right. It does indeed create a file in a temporary location in the filesys. I removed the reference to the 'memory-only' bit. However if a File object representation is a requirement, this is the closest you can get to it. Maybe we need to know what is meant by "treat it as a normal zip file". – ktorn May 07 '15 at 05:33
  • If the app is to be run under a Linux environment, another idea is to make use of the "free" ramdisk `/dev/shm/`. In that case you can write files under that path and be assured that they remain memory-only. – ktorn May 07 '15 at 05:51