Sunday, July 15, 2012

Reading file in Java

Following is an example how to read the file and display using System.out.println()

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileReader {
    public static void main(String[] args) {
        String file = "C:\\Users\\test.csv";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file)));
            while (reader.readLine() != null) {
                System.out.println(reader.readLine());
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Upload File using JSF 2.0 and Richfaces

Given below is a simple application how we can upload file using JSF 2.0. The example contain three files
1. The main FileUploadController which has much of the funtionalities for uploading saving files
2. The UploadedText is the bean containing information about the file and
3. The upload.xhtml JSF page.
First Create FileUploadController
1:  import java.io.File;  
2:  import java.io.FileOutputStream;  
3:  import java.io.IOException;  
4:  import java.io.OutputStream;  
5:  import java.io.Serializable;  
6:  import java.util.ArrayList;  
7:  import org.apache.log4j.Logger;  
8:  import org.richfaces.event.FileUploadEvent;  
9:  import org.richfaces.model.UploadedFile;  
10:  import org.springframework.context.annotation.Scope;  
11:  import org.springframework.stereotype.Component;  
12:  import com.jsf.app.client.vo.UploadedText;  
13:  // spring managed bean  
14:  @Component("fileUploadController")  
15:  @Scope("session")  
16:  public class FileUploadController implements Serializable {  
17:       private static final long serialVersionUID = -4664762090820133359L;  
18:       private static final Logger logger = Logger.getLogger(FileUploadBean.class  
19:                 .getName());  
20:       private static final String fPath = "C:\\Users\\";  
21:       private ArrayList<UploadedText> files = new ArrayList<UploadedText>();  
22:       public void paint(OutputStream stream, Object object) throws IOException {  
23:            stream.write(getFiles().get((Integer) object).getData());  
24:            stream.close();  
25:       }  
26:       public void listener(FileUploadEvent event) throws Exception {  
27:            UploadedFile item = event.getUploadedFile();  
28:            UploadedText file = new UploadedText();  
29:            file.setLength(item.getData().length);  
30:            file.setName(item.getName());  
31:            file.setData(item.getData());  
32:            files.add(file);  
33:       }  
34:       public String clearUploadData() {  
35:            files.clear();  
36:            return null;  
37:       }  
38:       public int getSize() {  
39:            if (getFiles().size() > 0) {  
40:                 return getFiles().size();  
41:            } else {  
42:                 return 0;  
43:            }  
44:       }  
45:       public long getTimeStamp() {  
46:            return System.currentTimeMillis();  
47:       }  
48:       public ArrayList<UploadedText> getFiles() {  
49:            return files;  
50:       }  
51:       public void setFiles(ArrayList<UploadedText> files) {  
52:            this.files = files;  
53:       }  
54:       public void writeFile() {  
55:            FileOutputStream fop = null;  
56:            File file;  
57:            UploadedText contain = files.size() > 0 ? files.get(0) : null;  
58:            if (contain == null) {  
59:                 return;  
60:            }  
61:            try {  
62:                 file = new File(fPath + contain.getName());  
63:                 fop = new FileOutputStream(file);  
64:                 if (!file.exists()) {  
65:                      file.createNewFile();  
66:                 }  
67:                 fop.write(contain.getData());  
68:                 fop.flush();  
69:                 fop.close();  
70:                 if (logger.isDebugEnabled()) {  
71:                      logger.debug("File Creation Completed Successfuly.");  
72:                 }  
73:            } catch (IOException e) {  
74:                 e.printStackTrace();  
75:            } finally {  
76:                 try {  
77:                      if (fop != null) {  
78:                           fop.close();  
79:                      }  
80:                 } catch (IOException e) {  
81:                      e.printStackTrace();  
82:                 }  
83:            }  
84:       }  
85:  }  

Next Create the UploadText file:
1:  import java.io.Serializable;  
2:  public class UploadedText implements Serializable {  
3:       private static final long serialVersionUID = -3957467715082208719L;  
4:       private String name;  
5:       private String mime;  
6:       private long length;  
7:       private byte[] data;  
8:       public String getName() {  
9:            return name;  
10:       }  
11:       public void setName(String name) {  
12:            int extDot = name.lastIndexOf('.');  
13:            if (extDot > 0) {  
14:                 String extension = name.substring(extDot + 1);  
15:                 if ("txt".equals(extension)) {  
16:                      mime = "text/plain";  
17:                 } else if ("csv".equals(extension)) {  
18:                      mime = "text/csv";  
19:                 } else {  
20:                      mime = "text/unknown";  
21:                 }  
22:            }  
23:            this.name = name;  
24:       }  
25:       public String getMime() {  
26:            return mime;  
27:       }  
28:       public void setMime(String mime) {  
29:            this.mime = mime;  
30:       }  
31:       public long getLength() {  
32:            return length;  
33:       }  
34:       public void setLength(long length) {  
35:            this.length = length;  
36:       }  
37:       public byte[] getData() {  
38:            return data;  
39:       }  
40:       public void setData(byte[] data) {  
41:            this.data = data;  
42:       }  
43:  }  

Finally Create the JSF file:
1:  <?xml version='1.0' encoding='UTF-8' ?>  
2:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
3:  <html xmlns="http://www.w3.org/1999/xhtml"  
4:       xmlns:f="http://java.sun.com/jsf/core"  
5:       xmlns:h="http://java.sun.com/jsf/html"  
6:       xmlns:ui="http://java.sun.com/jsf/facelets"  
7:       xmlns:a4j="http://richfaces.org/a4j"  
8:       xmlns:rich="http://richfaces.org/rich">  
9:  <h:body>  
10:       <ui:composition template="template/common/commonLayout.xhtml">  
11:            <ui:define name="content">  
12:                 <h:form>  
13:                      <h:panelGrid columns="2" columnClasses="top,top">  
14:                           <rich:fileUpload fileUploadListener="#{fileUploadController.listener}"  
15:                                id="upload" acceptedTypes="txt,csv"  
16:                                ontyperejected="alert('Only Text and CSV files are accepted');"  
17:                                maxFilesQuantity="1">  
18:                                <a4j:ajax event="uploadcomplete" execute="@none" render="info" />  
19:                           </rich:fileUpload>  
20:                      </h:panelGrid>  
21:                      <h:panelGroup id="info">  
22:                           <rich:dataGrid columns="1" value="#{fileUploadController.files}"  
23:                                var="file" rowKeyVar="row">  
24:                                <rich:panel bodyClass="rich-laguna-panel-no-header">  
25:                                     <h:panelGrid columns="2">  
26:                                          <a4j:mediaOutput element="img" mimeType="image/jpeg"  
27:                                               createContent="#{fileUploadController.paint}" value="#{row}"  
28:                                               style="width:100px; height:100px;" cacheable="false">  
29:                                               <f:param value="#{fileUploadController.timeStamp}" name="time" />  
30:                                          </a4j:mediaOutput>  
31:                                          <h:panelGrid columns="2">  
32:                                               <h:outputText value="File Name:" />  
33:                                               <h:outputText value="#{file.name}" />  
34:                                               <h:outputText value="File Length(bytes):" />  
35:                                               <h:outputText value="#{file.length}" />  
36:                                          </h:panelGrid>  
37:                                     </h:panelGrid>  
38:                                </rich:panel>  
39:                           </rich:dataGrid>  
40:                           <a4j:commandButton action="#{fileUploadController.clearUploadData}"  
41:                                render="info, upload" value="Clear Uploaded Data"  
42:                                rendered="#{fileUploadController.size>0}" />  
43:                           <a4j:commandButton action="#{fileUploadController.writeFile}"  
44:                                value="Write file to Disk" rendered="#{fileUploadController.size>0}" />  
45:                      </h:panelGroup>  
46:                 </h:form>  
47:            </ui:define>  
48:       </ui:composition>  
49:  </h:body>  
50:  </html>