I’m getting back into Java after 8 years away.
I have a file upload HTML page:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
from where I upload a CSV file.
/upload maps to a servlet that implements the doPost method:
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (!item.isFormField()) {
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
// do some deserialization here..?
}
}
}
I’m really hoping there’s a better way than the manually parsing approach. I’m reading about the Serializable interface – is this something I can use?
Thanks.
I expect you’ve already looked at the user guide for commons fileupload based on your code.
You can easily pass the input stream from commons fileupload into a CSV library such as Super CSV instead of writing your own stream reading code. You can even read the CSV as a POJO (i.e. Javabean). Take a look at the examples.
Your code will only differ from the examples in that you’re reading from an InputStream instead of a File, so creating the reader will look something like:
If you don’t actually want to read the CSV file (you might want to persist it or email it, for example), then you can use Commons IO’s IOUtils to read it into a byte array.
Oh, and welcome back to Java 🙂