栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

有没有一种简单的方法来输出列式CSV?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

有没有一种简单的方法来输出列式CSV?

我认为这很简单:

public static void main(String... args) throws IOException {    ArrayList<ArrayList<String>> rows = getRandomData();    if (rows.size() == 0)        throw new RuntimeException("No rows");    // normalize data    int longest = 0;    for (List<String> row : rows)        if (row.size() > longest) longest = row.size();    for (List<String> row : rows)        while (row.size() < longest) row.add("");    if (longest == 0)        throw new RuntimeException("No colums");    // fix special characters    for (int i = 0; i < rows.size(); i++)        for (int j = 0; j < rows.get(i).size(); j++) rows.get(i).set(j, fixSpecial(rows.get(i).get(j)));    // get the maximum size of one column    int[] maxColumn = new int[rows.get(0).size()];    for (int i = 0; i < rows.size(); i++)        for (int j = 0; j < rows.get(i).size(); j++) if (maxColumn[j] < rows.get(i).get(j).length())     maxColumn[j] = rows.get(i).get(j).length();    // create the format string    String outFormat = "";    for (int max : maxColumn)        outFormat += "%-" + (max + 1) + "s, ";    outFormat = outFormat.substring(0, outFormat.length() - 2) + "n";    // print the data    for (List<String> row : rows)        System.out.printf(outFormat, row.toArray());}private static String fixSpecial(String s) {    s = s.replaceAll("(")", "$1$1");    if (s.contains("n") || s.contains(",") || s.contains(""") ||  s.trim().length() < s.length()) {        s = """ + s + """;    }    return s;}private static ArrayList<ArrayList<String>> getRandomData() {    ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();    String[] rand = { "Do", "Re", "Song", "David", "Test", "4", "Hohjoh", "a "h" o", "tjo,ad" };    Random r = new Random(5);    for (int i = 0; i < 10; i++) {        ArrayList<String> row = new ArrayList<String>();        for (int j = 0; j < r.nextInt(10); j++) row.add(rand[r.nextInt(rand.length)]);        data.add(row);    }    return data;}

输出(因为它是随机的,所以很难看)(转义):

Re       , 4, "tjo,ad" , "tjo,ad" ,    "tjo,ad" , "a ""h"" o" ,          ,          ,    Re       , "a ""h"" o" , Hohjoh   , "tjo,ad" , 4  4        , David       ,          ,          ,    4        , Test        , "tjo,ad" , Hohjoh   , Re Do       , Hohjoh      , Test     ,          ,    Hohjoh   , Song        ,          ,          ,    4        , Song        ,          ,          ,    4        , Do          , Song     , Do       ,    Song     , Test        , Test     ,          ,


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616958.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号