Copy data into a temporary File

This is the easiest approach if you don't know in advance the size of data and you suspect it might be huge (>100Mb).

The main disadvantages are :

  • It's utterly slow.
  • If used on large scale file handlers tend to finish. File handlers might be a serious problem if you're not very careful closing all the streams: temporary files might not be deleted and file handlers might be still in use.
  • In clustered environments writing a file in a server directory should be done with care: your session may be serialized and sent to another server. The file you just wrote may not be there again the next request.
// create a temporary file.
File tempFile = File.createTempFile("tempFile", ".tmp");
OutputStream out = new FileOutputStream(tempFile);

// write data on your OutputStream here
writeDataToTheOutputStream(out);
//be sure to close the OutputStream 
//(be sure the previous method doesn't throw exceptions)
out.close();
//get an InputStream from the previous file.
InputStream istream = new FileInputStream(tempFile);
				
//process the data as you like.
processDataFromInputStream(istream);

//be sure to close here.
istream.close();
//delete temporary file when you finish to use it.
//if streams where not correctly closed this might fail (return false)
tempFile.delete();

In next page we'll see a solution that overcomes the problems explained before: use pipes.

Home Memory buffer

Pipes Next