Skip to content Skip to sidebar Skip to footer

How To Use Read A Comma Delimited Text File Using Split() In Java/jsp To Seperate Each Element

i have a text file that is as such: 'name email gender location' joe,joe@g.com,male,london fred,fred@g.com,male,new york I am trying to read this data into a html table using

Solution 1:

Use String.split():

String[] parts = tmp.split(",");

If tmp contained "joe,joe@g.com,male,london" then:

parts[0] = "joe"
parts[1] = "joe@g.com"
parts[2] = "male"
parts[3] = "london"

I am unfamiliar with jsp, but if the objective of the while is to transform each line read from br into a HTML <tr>...</tr> and append to list then:

while ((tmp = br.readLine()) != null)
{
    String[] parts = tmp.split(",");
    if (4 == parts.length) // Not sure what validation is required, if any.
    {
        StringBuilder tr = new StringBuilder("<tr>");
        for (String s: parts)
        {
            tr.append("<td>")
              .append(s)
              .append("</td>");
        }
        tr.append("</tr>")
        list.add(tr.toString()); 
    }
}

Solution 2:

Use the java.util.Scanner class. The scanner has a method called useDelimiter(). Set the delimiter to a comma.

 line = br.readLine();
 sc = new Scanner(line);
 sc.useDelimiter(",");
 name = sc.next();
 gender = sc.next();
 email = sc.next();
 location = sc.next();

 // put this in a loop to do it for every line of text 

Solution 3:

tmp.split("\\s*,\\s*") returns array of your elements: name email gender location

Solution 4:

Not for nothing but you can find TONS of samples on this if you just Googled it. That being said, RoseIndia.net has this simple example on how to read a CSV from a file using JSP:

<%@ page import="java.io.*"%>
<html>
<body>
<% 
    String fName = "c:\\csv\\myfile.csv";
    String thisLine; 
    int count=0; 
    FileInputStream fis = new FileInputStream(fName);
    DataInputStream myInput = new DataInputStream(fis);
    int i=0; 
%>
<table>
<%
while ((thisLine = myInput.readLine()) != null)
{
    String strar[] = thisLine.split(",");
    for(int j=0;j<strar.length;j++)
    {
        if(i!=0)
        {
            out.print(" " +strar[j]+ " ");
        }
        else
        {
            out.print(" <b>" +strar[j]+ "</b> ");
        }
    } 
    out.println("<br>");
    i++;
} 
%>
</table>
</body>
</html>

Hope that helps!

Solution 5:

Let's assume that your text file contains "name email gender location" information of some customers. So we are saving this file as customers.txt in your hard-drive.

Next, you have to create a package named "com.customer.table.model" under your project folder. Create a new java bean class called "Customer.java" under this package. Copy the below code & include it in Customer class.

package com.customer.table.model;

/**
 *
 * @authorsarath_sivan
 */publicclassCustomer {

    privateString name;
    privateString email;
    privateString gender;
    privateString location;

    publicCustomer() {}

    publicStringgetName() {
        returnthis.name;
    }

    publicvoidsetName(String name) {
        this.name = name;
    }

    publicStringgetEmail() {
        returnthis.email;
    }

    publicvoidsetEmail(String email) {
        this.email = email;
    }

    publicStringgetGender() {
        returnthis.gender;
    }

    publicvoidsetGender(String gender) {
        this.gender = gender;
    }

    publicStringgetLocation() {
        returnthis.location;
    }

    publicvoidsetLocation(String location) {
        this.location = location;
    }

}

Next, you have to create one more package under your project directory. Give the package name "com.customer.table.service" for the new one. Then create a Java class with the name "FileReader" & include the below code in it.

package com.customer.table.service;


import com.customer.table.model.Customer;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author sarath_sivan
 */publicclassFileReader {

    publicstatic List<Customer> readFile(String fileName)throws FileNotFoundException, IOException { // reading each line from the customer.txt file, formatting it and returning a as a list for displaying in in our jsp page.FileInputStreamfileInputStream=newFileInputStream(fileName);
        DataInputStreamdataInputStream=newDataInputStream(fileInputStream);
        InputStreamReaderinputStreamReader=newInputStreamReader(dataInputStream);
        BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);
        List<Customer> customerList = newArrayList<Customer>(); String readLine;

        while((readLine=bufferedReader.readLine())!=null) {
            System.out.println(readLine);
            customerList.add(formatReadLine(readLine));
        }

        dataInputStream.close();
        return customerList;
    }

    publicstatic Customer formatReadLine(String readLine) {
        String[] splits = split(readLine);
        Customercustomer=newCustomer();
        customer.setName(getTableDataFormat(splits[0]));
        customer.setEmail(getTableDataFormat(splits[1]));
        customer.setGender(getTableDataFormat(splits[2]));
        customer.setLocation(getTableDataFormat(splits[3]));
        return customer;
    }

    publicstatic String[] split(String readLine) { // splitting each line from the customer.txt file with "," as the delimiterreturn readLine.split(",");
    }

    publicstatic String getTableDataFormat(String splits) { // Method for appending <td> tags with the formatted dataStringBuildertableData=newStringBuilder();
        tableData.append("<td>");
        tableData.append(splits);
        tableData.append("</td>");
        return tableData.toString();
    }

}

Once both the above class files are created, we can go for the jsp page that you would like to display each element extracted from the text file by comma. Now, create a new jsp page, say index.jsp under your main web project folder. Copy & paste the below code in it.

 <%-- 
    Document   : index
    Created on : 29 Feb, 2012, 11:30:04 PM
    Author     : sarath_sivan
--%>

<%@page import="com.customer.table.service.FileReader"%>
<%@page import="com.customer.table.model.Customer"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><metahttp-equiv="Content-Type"content="text/html; charset=UTF-8"><title>JSP Page</title></head><body><h1>Customer Information</h1><tableborder="1"align="left"><tr><th>Name</th><th>Email</th><th>Gender</th><th>Location</th></tr>
        <%  try {
                List<Customer> customerList = new ArrayList<Customer>();
                String fileName = "C:/Users/compaq/Desktop/customers.txt";
                customerList = FileReader.readFile(fileName);
                for(Customer customer : customerList) {
                    out.println("<tr>");
                    out.println(customer.getName()+customer.getEmail()+customer.getGender()+customer.getLocation());
                    out.println("</tr>");
                }
            } catch(Exception e) {
               e.printStackTrace();
            }

        %>
        </table></body></html>

Now, it is ready for deployment. You can run your project on any server. You can see all data included in the customer.txt file in your index.jsp as a table format as shown below. Similarly you can add more details by changing the above code as per your requirement.

    Customer Information
Name    Email   Gender  Location
joe joe@g.com   male    male
fred    fred@g.com  male    male

Hope this will save your purpose....!

Thanks you..!

Post a Comment for "How To Use Read A Comma Delimited Text File Using Split() In Java/jsp To Seperate Each Element"