简体   繁体   English

如何将数据从txt文件拉入HTML表Java / JSP

[英]How to pull data from a txt file into a HTML table Java/JSP

I have a Text file (.txt) that contains data strings using comma separated values, ie 我有一个文本文件(.txt),其中包含使用逗号分隔值的数据字符串,即

jordan,hello,12th Feb 15:23, pending

I would like to then pull this data into a HTML table with the ",' separating each column. For example the headings of the table would be: 然后,我想将这些数据拖入带有“,”的HTML表中,并将每一列分开。例如,表的标题为:

Name   Question   Date    Status

Thus Jordan would go in the name column and hello under question etc. 因此,乔丹将进入名称列,并在问题下打招呼等。

Currently I have output the full string but I need the individual elements. 目前,我已经输出了完整的字符串,但是我需要单独的元素。

Any advice would be appreciated. 任何意见,将不胜感激。

You need a parser to read csv file and create individual elements. 您需要一个解析器来读取csv文件并创建单个元素。 You can either use String.split(...) or even better leverage CSV parsing libraries . 您可以使用String.split(...) ,甚至可以更好地利用CSV解析库 Create a class Data and populate it with the parsed data (each row has a corresponding Data object). 创建一个Data类,并使用解析的数据填充它(每行都有一个对应的数据对象)。 You should have a List<Data> after the entire file has been parsed which you can pass to the JSP page. 解析完整个文件后,应该具有List<Data> ,可以将其传递到JSP页面。 JSP then iterates through the List and creates the table. 然后,JSP遍历List并创建表。

Assuming that you don't have a , in the data, simply call split(",") on each line and create a custom formatted HTML table, something like this (haven't tested): 假设你没有,在数据,只需调用split(",")在每行和创建一个自定义格式的HTML表,像这样(没有测试):

out.println("<table>")

for (int i=0; i<lines.length; ++i) {
    out.println("<tr>" )
    String[] data = line[i].split(",");

    for (String val : data) {
        out.println("<td>" + val + "</td>")
    }

    out.println("</tr>" )
}

out.println("</table>")

You can use the String#Split method to convert your actual String to an array of Strings with all the values: 您可以使用String#Split方法将实际的String转换为具有所有值的String数组:

String s = "jordan,hello,12th Feb 15:23, pending"
String[] sArray = s.split(",");
for(String si : sArray) {
    //you can print them in your output
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM