如何使用java/jsp中的split()读取逗号分隔的文本文件以分隔每个元素 [英] How to use read a comma delimited text file using split() in java/jsp to seperate each element

查看:547
本文介绍了如何使用java/jsp中的split()读取逗号分隔的文本文件以分隔每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的文本文件:

姓名电子邮件的性别位置"
joe,joe @ g.com,男,伦敦
fred,fred @ g.com,男,纽约

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

我正在尝试使用jsp/java将此数据读取到html表中.目前,我可以将它们全部读入表中,但是整行显示在标题下的一个单元格中.因此,它们现在都将显示在名称下.我将如何分割逗号分隔的文本文件的每个元素,使它们出现在正确的标题下.

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); 
        } 

推荐答案

使用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,则:

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

这篇关于如何使用java/jsp中的split()读取逗号分隔的文本文件以分隔每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆