How To Use Read A Comma Delimited Text File Using Split() In Java/jsp To Seperate Each Element
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;
/**
*
* @author sarath_sivan
*/
public class Customer {
private String name;
private String email;
private String gender;
private String location;
public Customer() {}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLocation() {
return this.location;
}
public void setLocation(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
*/
public class FileReader {
public static 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.
FileInputStream fileInputStream = new FileInputStream(fileName);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
InputStreamReader inputStreamReader = new InputStreamReader(dataInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
List<Customer> customerList = new ArrayList<Customer>(); String readLine;
while((readLine=bufferedReader.readLine())!=null) {
System.out.println(readLine);
customerList.add(formatReadLine(readLine));
}
dataInputStream.close();
return customerList;
}
public static Customer formatReadLine(String readLine) {
String[] splits = split(readLine);
Customer customer = new Customer();
customer.setName(getTableDataFormat(splits[0]));
customer.setEmail(getTableDataFormat(splits[1]));
customer.setGender(getTableDataFormat(splits[2]));
customer.setLocation(getTableDataFormat(splits[3]));
return customer;
}
public static String[] split(String readLine) { // splitting each line from the customer.txt file with "," as the delimiter
return readLine.split(",");
}
public static String getTableDataFormat(String splits) { // Method for appending <td> tags with the formatted data
StringBuilder tableData = new StringBuilder();
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 HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Customer Information</h1>
<table border="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"