How to use read a comma delimited text file using split() in java/jsp to seperate each element

霸气de小男生 提交于 2019-12-13 21:15:28

问题


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 jsp/java. At the moment i can read them all into the table but the whole line appears in one cell under the headings. So at the moment they will all appear under name. how would i split each element of the comma delimited text file so they appear under the correct heading.

    <tr>
      <td>Name</td>
      <td>Email</td>
      <td>Gender</td>
      <td>Location</td>
    </tr>

    <%

    List<String > list =new ArrayList<String>(); 
    FileInputStream in = new FileInputStream("people.txt"); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 


    String strLine ="", tmp; 
    while ((tmp = br.readLine()) != null){  
        strLine =tmp+"\n"+strLine; 
        list.add(tmp); 
        } 

回答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()); 
    }
}



回答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 



回答3:


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




回答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!




回答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..!



来源:https://stackoverflow.com/questions/9501106/how-to-use-read-a-comma-delimited-text-file-using-split-in-java-jsp-to-seperat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!