0

我目前正在使用 JSoup 从 HTML 表中抓取数据,然后将其存储到 ArrayList 中。然后我想将这些值存储在 SQL 数据库中。据我了解,这些必须先转换为字符串,然后才能插入数据库。我将如何将这些 ArrayLists 转换为字符串?

这是我当前的代码:

    Document doc = Jsoup.connect(URL).timeout(5000).get();

    for (Element table : doc.select("table:first-of-type")) 
    {
        for (Element row : table.select("tr:gt(0)")) { 
            Elements tds = row.select("td");

            List1.add(tds.get(0).text());
            List2.add(tds.get(1).text());
            List3.add(tds.get(2).text());
        }
    }
4

3 回答 3

2

To get all the values you need, you can iterate through the list very easily :

public static void main(String[] args) {
    List<String> List1 = new ArrayList<>();
    for (String singleString : List1){
        //Do whatever you want with each string stored in this list
    }
}
于 2013-10-24T15:49:54.490 回答
0

Well i am not really sure if there is some special way to achieve what you are asking . You would need to iterate over the array . You could use the StringBuilder instead of String for a bit of optimization. I am not really sure how much of a boost you would gain in performance ..

Anyway this is how the code would look ..

StringBuilder sb = new StringBuilder();
for (Object o : list1){
  sb.append(o.toString()+delimiter); // delimiter could be , or \t or || 

 //You could manipulate the string here as required..
 //  enter code here`
}
return sb.toString();

You would then need to split the strings if required. ( if they need to go into seperate fields

于 2013-10-24T16:08:57.097 回答
0

Java 集合框架没有提供任何直接的实用方法来将 ArrayList 转换为 Java 中的 String。但是以依赖注入而闻名的 Spring 框架及其 IOC 容器也提供了 API 和通用实用程序,例如在 Java 中将 Collection 转换为 String 的方法。您可以使用 Spring Framework 的 StringUtils 类将 ArrayList 转换为 String。StringUtils 类提供了三种方法来转换任何集合

例如Java中的ArrayList转String,如下图:

public static String collectionToCommaDelimitedString(Collection coll)
public static String collectionToDelimitedString(Collection coll, String delim)
public static String collectionToDelimitedString(Collection coll, String delim, String  prefix, String suffix)

知道了....

于 2013-10-24T15:55:53.617 回答