[英]How to use read a comma delimited text file using split() in java/jsp to seperate each element
我有一個這樣的文本文件:
“姓名電子郵件性別位置”
喬,喬@ g.com,男,倫敦
弗雷德,fred @ g.com,男,紐約
我正在嘗試使用jsp / java將此數據讀取到html表中。 目前,我可以將它們全部讀入表中,但是整行顯示在標題下的一個單元格中。 因此,目前它們都將以名稱出現。 我將如何分割逗號分隔的文本文件的每個元素,使它們出現在正確的標題下。
<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);
}
使用String.split()
:
String[] parts = tmp.split(",");
如果tmp
包含"joe,joe@g.com,male,london"
則:
parts[0] = "joe"
parts[1] = "joe@g.com"
parts[2] = "male"
parts[3] = "london"
我不熟悉jsp,但是如果while
的目的是將從br
讀取的每一行轉換為HTML <tr>...</tr>
並追加到list
則:
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());
}
}
使用java.util.Scanner類。 掃描程序有一個稱為useDelimiter()的方法。 將定界符設置為逗號。
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
tmp.split("\\\\s*,\\\\s*")
返回元素數組:名稱電子郵件性別位置
並非沒有,但只要您將它搜索一下,就可以找到大量的樣本。 話雖如此, RoseIndia.net上有一個簡單的示例,說明如何使用JSP從文件讀取CSV:
<%@ 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>
希望有幫助!
假設您的文本文件包含某些客戶的“姓名電子郵件性別位置”信息。 因此,我們將此文件另存為您的硬盤中的customer.txt。
接下來,您必須在項目文件夾下創建一個名為“ com.customer.table.model”的包。 在此程序包下創建一個新的Java bean類,稱為“ Customer.java”。 復制以下代碼並將其包含在Customer類中。
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;
}
}
接下來,您必須在項目目錄下再創建一個軟件包。 給新包命名為“ com.customer.table.service”。 然后創建一個名稱為“ FileReader”的Java類,並在其中包含以下代碼。
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();
}
}
創建完以上兩個類文件后,我們可以進入jsp頁面,您希望顯示以逗號顯示從文本文件中提取的每個元素。 現在,在主Web項目文件夾下創建一個新的jsp頁面,例如index.jsp。 將以下代碼復制並粘貼到其中。
<%--
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>
現在,可以部署了。 您可以在任何服務器上運行項目。 您可以以表格格式查看index.jsp中customer.txt文件中包含的所有數據,如下所示。 同樣,您可以根據需要通過更改上述代碼來添加更多詳細信息。
Customer Information
Name Email Gender Location
joe joe@g.com male male
fred fred@g.com male male
希望這可以節省您的目的。
謝謝..!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.