I need help in code which is used to convert javax.servlet.http.Part to java.io.File
I found this useful code but I need help in properly implementing the code.
private void processFilePart(Part part, String filename) throws IOException
{
filename = filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
String prefix = filename;
String suffix = "";
if (filename.contains("."))
{
prefix = filename.substring(0, filename.lastIndexOf('.'));
suffix = filename.substring(filename.lastIndexOf('.'));
}
File file = File.createTempFile(prefix + "_", suffix, new File(location));
if (multipartConfigured)
{
part.write(file.getName());
}
else
{
InputStream input = null;
OutputStream output = null;
try
{
input = new BufferedInputStream(part.getInputStream(), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(new FileOutputStream(file), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
for (int length = 0; ((length = input.read(buffer)) > 0);)
{
output.write(buffer, 0, length);
}
}
finally
{
if (output != null)
try
{
output.close();
}
catch (IOException logOrIgnore)
{
}
if (input != null)
try
{
input.close();
}
catch (IOException logOrIgnore)
{
}
}
}
put(part.getName(), file);
part.delete();
}
I tried to edit the code in order to create as a result java.io.File but I always have issues.
private void processFilePart(Part part, String filename) throws IOException
{
int DEFAULT_BUFFER_SIZE = 2048;
filename = filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
String prefix = filename;
String suffix = "";
if (filename.contains("."))
{
prefix = filename.substring(0, filename.lastIndexOf('.'));
suffix = filename.substring(filename.lastIndexOf('.'));
}
File file = new File(filename);
InputStream input = null;
OutputStream output = null;
try
{
input = new BufferedInputStream(part.getInputStream(), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(new FileOutputStream(file), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
for (int length = 0; ((length = input.read(buffer)) > 0);)
{
output.write(buffer, 0, length);
}
}
finally
{
if (output != null)
try
{
output.close();
}
catch (IOException logOrIgnore)
{
}
if (input != null)
try
{
input.close();
}
catch (IOException logOrIgnore)
{
}
}
// how to get the result
part.delete();
}
What is the proper way to convert the objects?