【问题标题】:How to write an ArrayList<String[]> to a .csv file in Java?如何将 ArrayList<String[]> 写入 Java 中的 .csv 文件?
【发布时间】:2021-03-07 01:14:21
【问题描述】:

假设我有一个这样的字符串数组的 ArrayList:

    ArrayList<String[]> arrayList = new ArrayList<String[]>();
    arrayList.add(new String[]{"hello", "goodbye"});
    arrayList.add(new String[]{"yoyo", "fofo"});
    arrayList.add(new String[]{"foo", "bar"});

在 Java 中将其转换为 .csv 文件的最简单方法是什么?由于 ArrayLists 是动态的,因此我有一些数据被操纵到这个特定的数据结构中,并且我在内部使用了 String 数组,因为数据中的列数不会改变,我们可以继续为每个新的 ' .csv 输出中的“行”。

【问题讨论】:

    标签: java arrays csv arraylist data-structures


    【解决方案1】:

    一种可能的方法如下: 你可能需要添加一些检查和类似的东西

    // 代码

    import java.util.ArrayList;
    import java.io.*;
    
    public class a{
        public static void main(String[] args){
            ArrayList<String> arrayList = new ArrayList<String>();
            arrayList.add(new String("hello"));
            arrayList.add(new String("yoyo"));
            arrayList.add(new String("foo"));
            try{
                FileWriter file = new FileWriter("sample.csv");
                PrintWriter write = new PrintWriter(file);
                for (String name: arrayList){
                write.println(name);
            }
            write.close();
        }
        catch(IOException exe){
            System.out.println("Cannot create file");
        }
    }
    

    }

    【讨论】:

    • 我在该解决方案中添加了一个嵌套的 for 循环来处理有问题的原始数据结构:ArrayList。无论如何,谢谢!
    • 是的,没问题!很高兴我能帮上忙。
    【解决方案2】:

    您需要执行以下操作:

    1. 打开/创建文件
    2. 遍历 ArrayList 并将每一对打印在一行上,或者按您的需要打印
    3. 关闭文件

    在我看来,最好不要使用任何库,因为你真的不需要。

    这是关于如何写入文件的基本教程:https://www.w3schools.com/java/java_files_create.asp

    例子:

    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
    

    这是一个关于如何遍历 ArrayList 的基本教程:https://beginnersbook.com/2013/12/how-to-loop-arraylist-in-java/

    例子:

    for (String[] entry : arrayList) {            
           System.out.println(entry);       
      }
    

    祝你好运!

    PS:我故意不给你完整的代码来复制/粘贴,所以你实际上学到了一些东西

    【讨论】:

    • PPS:如果您想要每行一对,您可能需要在每对之后写一个换行符(Linux 中为 \n,Windows 中为 \r\n)。
    【解决方案3】:

    如果您想将字符串数组写入文件,您可以遍历数组并写入文件

    例子

    List<String[]>arrayList= new ArrayList<String[]>();
    arrayList.add(new String[]{"hello", "goodbye"});
    arrayList.add(new String[]{"yoyo", "fofo"});
    arrayList.add(new String[]{"foo", "bar"});
    
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    for(String[] data : arrayList) {
      writer.write(String.join(",", data );
    }
    

    如果您正在寻找高级用法,这是使用CSV Java Utility 的一种可能性。使用它,您可以轻松读取和写入 CSV 数据。

    这是一个例子

    import java.io.BufferedOutputStream;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;
    
    import com.Ostermiller.util.CSVPrinter;
    
    public class CSVUtil{
    
            
        public static CSVPrinter getCSVPrinter(File outputDir, String tabname,
                boolean append) throws FileNotFoundException,
                UnsupportedEncodingException {
    
            // Output filename
            File f = new File(outputDir, tabname + ".csv");
    
            FileOutputStream fo = new FileOutputStream(f, append);
            BufferedOutputStream out = new BufferedOutputStream(fo, 500000);
            OutputStreamWriter streamWriter = new OutputStreamWriter(out, "UTF-8");
            BufferedWriter bw = new BufferedWriter(streamWriter);
    
            // Intialize the CSV Printer
            CSVPrinter csvout = new CSVPrinter(bw);
            csvout.changeDelimiter('\t');
            // csvout.setAutoFlush(true);
            csvout.setAlwaysQuote(true);
            csvout.setLineEnding("\r\n");
    
            return csvout;
        }
    
    }
    

    用法:

    CSVPrinter  csvPrinter= CSVUtil.getCSVPrinter(outDir, "fileName", 
                                                            true);
    csvPrinter.writeln(new String[] {"Data1","Data2","Data3"});
    

    【讨论】:

    • 我认为工厂模式没有任何业务可以回答“什么是最简单的方法......”这个问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 2016-11-20
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多