As you probably know, CSV (Comma-Separated Value) files are text files that stores values separated by commas. Usually a CSV file has a header and sets of values that are written one set per line. Each line in the CSV file corresponds to a row in the table. For example let's consider the following CSV content, example.csv
:
Name,Age,E-mail Mike,27,[email protected] Susan,29,[email protected] Tom,20,[email protected] Elly,32,[email protected]
In this recipe, we will upload this file to the server and we will extract the data into an ArrayList
.
We developed this recipe with NetBeans 6.8, JSF 1.2, and GlassFish v3. The JSF 1.2 classes were obtained from the NetBeans JSF 1.2 bundled library. In addition, we have used Apache MyFaces Tomahawk 1.1.9, which provides support for JSF 1.2. You can download this distribution from http://myfaces.apache.org/tomahawk/index.html. The Apache MyFaces Tomahawk libraries (including necessary dependencies) are in the book code bundle, under the /JSF_libs/Apache Tomahawk—JSF 1.2
folder.
First, you must know that for uploading the CSV file you can use any of the previous recipes presented. We decide to use the upload solution from recipe File upload with Apache MyFaces Tomahawk. The snipped code is shown next:
<h:panelGrid columns="3"> <h:outputLabel for="fileID" value="Choose a file to upload:" /> <t:inputFileUpload id="fileID" value="#{uploadBean.uploadedFile}" storage="file" required="true" /> <h:message showSummary="true" showDetail="false" for="fileID" style="color: red; text-decoration:overline"/> <h:panelGroup /> <h:commandButton value="Submit" action="#{uploadBean.submit}" /> <h:message for="uploadForm" infoStyle="color: blue;" errorStyle="color: red;" /> </h:panelGrid>
Using this solution, you must have access to the uploaded file stream by calling the uploadedFile.getInputStream()
method in the UploadBean
bean. Before processing this stream, we define a POJO class that maps the name, age
, and email
fields as shown next:
package uploadpkg; public class csvObject { private String name; private byte age; private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public byte getAge() { return age; } public void setAge(byte age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
Next, we write the UploadBean
bean as shown next:
package uploadpkg; import org.apache.myfaces.custom.fileupload.UploadedFile; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; public class UploadBean { private UploadedFile uploadedFile; private String fileName; private List<csvObject> csvs = new ArrayList<csvObject>(); public List<csvObject> getCsvs() { return csvs; } public void setCsvs(List<csvObject> csvs) { this.csvs = csvs; } public UploadedFile getUploadedFile() { return uploadedFile; } public String getFileName() { return fileName; } public void setUploadedFile(UploadedFile uploadedFile) { this.uploadedFile = uploadedFile; } public void submit() { // Get information you from the uploaded file System.out.println("Uploaded file name: " + uploadedFile.getName()); System.out.println("Uploaded file type: " + uploadedFile.getContentType()); System.out.println("Uploaded file size: " + uploadedFile.getSize() + " bytes"); try { //get the uploaded file InputStream inputStream = uploadedFile.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //define the byte size byte bufferZone[] = new byte[1024]; int read = 0; //read CSV while( (read = inputStream.read(bufferZone, 0, (int)uploadedFile.getSize())) != -1 ) { byteArrayOutputStream.write( bufferZone, 0, read); } //assign it to string String cvs = new String(byteArrayOutputStream.toByteArray()); StringTokenizer stringTokenizer_1 = new StringTokenizer(cvs," "); stringTokenizer_1.nextToken(); while (stringTokenizer_1.hasMoreTokens()){ StringTokenizer stringTokenizer_2 = new StringTokenizer(stringTokenizer_1.nextToken(),","); csvObject csvobj = new csvObject(); csvobj.setName(stringTokenizer_2.nextToken()); csvobj.setAge(Byte.valueOf(stringTokenizer_2.nextToken())); csvobj.setEmail(stringTokenizer_2.nextToken()); csvs.add(csvobj); } this.setCsvs(csvs); //Upload success FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(FacesMessage.SEVERITY_INFO, "File upload was a total success!", null)); } catch (Exception e) { //Upload failed FacesContext.getCurrentInstance().addMessage("uploadForm", new FacesMessage(FacesMessage.SEVERITY_ERROR, "File upload was a failed.", null)); e.printStackTrace(); } } }
The uploaded file InputStream
, passes through these steps:
InputStream
object to the uploadedFile.getInputStream()
method.ByteArrayOutputStream
object.ByteArrayOutputStream
into a String
.StringTokenizer
, to get each row from this String
. For this we use the"
"
as separator.StringTokenizer
to get values from each row returned by the previous StringTokenizer
. Now, the separator is","
.csvObject
POJO with the extracted values.ArrayList<csvObject>
.