FileUtil.java
package com.osram.omd.common.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtils2
{
public static void writeToFile(String fileName, InputStream iStream)
throws IOException
{
writeToFile(fileName, iStream, false);
}
public static void writeToFile(String fileName, InputStream iStream,
boolean createDir)
throws IOException
{
String me = "FileUtils.WriteToFile";
if (fileName == null)
{
throw new IOException(me + ": filename is null");
}
if (iStream == null)
{
throw new IOException(me + ": InputStream is null");
}
File theFile = new File(fileName);
if (theFile.exists())
{
String msg =
theFile.isDirectory() ? "directory" :
(! theFile.canWrite() ? "not writable" : null);
if (msg != null)
{
throw new IOException(me + ": file '" + fileName + "' is " + msg);
}
}
if (createDir && theFile.getParentFile() != null)
{
theFile.getParentFile().mkdirs();
}
BufferedOutputStream fOut = null;
try
{
fOut = new BufferedOutputStream(new FileOutputStream(theFile));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
while ((bytesRead = iStream.read(buffer)) != -1)
{
fOut.write(buffer, 0, bytesRead);
}
}
catch (Exception e)
{
throw new IOException(me + " failed, got: " + e.toString());
}
finally
{
close(iStream, fOut);
}
}
protected static void close(InputStream iStream, OutputStream oStream)
throws IOException
{
try
{
if (iStream != null)
{
iStream.close();
}
}
finally
{
if (oStream != null)
{
oStream.close();
}
}
}
}