使用 Java 中的缓冲编写器编写 csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19027473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:31:23  来源:igfitidea点击:

writing a csv file using Buffered writer in Java

javacsvbufferedwriter

提问by Wearybands

I am writing a csv file using buffered writer in java. My data is written correctly but I want to have different columns under which the data comes, Currently it is writing each instance of date in one row but not separated by columns.

我正在使用 java 中的缓冲编写器编写一个 csv 文件。我的数据写入正确,但我希望数据来自不同的列,目前它正在一行中写入每个日期实例,但不以列分隔。

The code is

代码是

  DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");  
        File file = new File( dirName + "\"+ df.format(new Date()) +"_Statistics.csv");  
        if ( !file.exists() )
            file.createNewFile();

        FileWriter fw = new FileWriter(file);
        writer = new BufferedWriter( fw );
        writer.write("Message Source");
        writer.write("Message Name");
        writer.write("Component");
        writer.write("Occurance");
        writer.write("Message Payload");
        writer.write("Bandwidth (Payload)");
        writer.write("Message Payload with Header");
        writer.write("Bandwidth (Payload with Header)");
        writer.newLine();
        for (Signal signal : messages) {
            writer.write(signal.getSource());
            writer.write(signal.getName());
            writer.write(signal.getComponent());
            writer.write(Integer.toString(signal.getOccurance()));
            writer.write(Integer.toString(signal.getSize()));
            writer.write(Float.toString(signal.getBandwidth()));
            writer.write(Integer.toString(signal.getSizewithHeader()));
            writer.write(Float.toString(signal.getBandwidthWithHeader()));
            writer.newLine();
        }
        writer.flush();
        writer.close();
        fw.close();

Is there any way to separate the data column wise so that it is properly readable?

有什么方法可以明智地分隔数据列,以便正确读取吗?

EDIT

编辑

Instead of using buffered writer I use CSVReaderlibrary for java. http://www.csvreader.com/java_csv.phpThe code now is

我没有使用缓冲写入器,而是使用CSVReaderjava 库。http://www.csvreader.com/java_csv.php现在的代码是

  DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");  
        File file = new File( dirName + "\"+ df.format(new Date()) +"_Statistics.csv");  
        if ( !file.exists() )
            file.createNewFile();

        // Use FileWriter constructor that specifies open for appending
        CsvWriter csvOutput = new CsvWriter(new FileWriter(file, true), ',');

        //Create Header for CSV
        csvOutput.write("Message Source");
        csvOutput.write("Message Name");
        csvOutput.write("Component");
        csvOutput.write("Occurance");
        csvOutput.write("Message Payload");
        csvOutput.write("Bandwidth (Payload)");
        csvOutput.write("Message Payload with Header");
        csvOutput.write("Bandwidth (Payload with Header)");
        csvOutput.endRecord();
        for (Signal signal : messages) {
            csvOutput.write(signal.getSource());
            csvOutput.write(signal.getName());
            csvOutput.write(signal.getComponent());
            csvOutput.write(Integer.toString(signal.getOccurance()));
            csvOutput.write(Integer.toString(signal.getSize()));
            csvOutput.write(Float.toString(signal.getBandwidth()));
            csvOutput.write(Integer.toString(signal.getSizewithHeader()));
            csvOutput.write(Float.toString(signal.getBandwidthWithHeader()));
            csvOutput.endRecord();
        }
        csvOutput.flush();
        csvOutput.close();

It properly formats the data but the problem is now when I run the code for 2nd time a 2nd file is created and the new file contains duplicated rows, for every row in the first file there are 2 rows in the 2nd file with similar data.

它正确格式化数据,但现在问题是当我第二次运行代码时,创建了第二个文件并且新文件包含重复的行,对于第一个文件中的每一行,第二个文件中有 2 行具有相似的数据。

Is that I am not cleaning some resources ?

是不是我没有清理一些资源?

Thanks

谢谢

回答by S.Lukas

From what I understand your actual data isn't lining up with the columns, because there is no way for it to know how wide the column is.

据我了解,您的实际数据与列不对齐,因为它无法知道列的宽度。

You could try using tabs, or predefine the width of each column (like make them all 10 characters).

您可以尝试使用制表符,或预定义每列的宽度(例如使它们全部为 10 个字符)。

回答by Gitansh

If you want to have a seperate coloumn in Excel, for the fields that you have written in your code so instead of fw.append(",");Just give fw.append(";");It will work and for setting the Header, instead of creating a variable like String f="Id, Name, Salary"and passing that variable to the method fw.append(f);Simply pass the fields instead of creating the variable like fw.append("Id; Name; Salary")using semicolon.

如果你想在 Excel 中有一个单独的列,对于你在代码中编写的字段,而不是fw.append(",");只给fw.append(";");它会起作用并用于设置标题,而不是创建一个像变量一样的变量String f="Id, Name, Salary"并将该变量传递给方法fw.append(f);简单地传递字段而不是像fw.append("Id; Name; Salary")使用分号那样创建变量。

回答by shashwatZing

When writing a csv file you need to enclose your data like this

编写 csv 文件时,您需要像这样将数据括起来

csvOutput.write("\"");
csvOutput.write(signal.getSource());
csvOutput.write("\"");
csvOutput.write(",\"")
csvOutput.write("\"");
csvOutput.write(signal.getName()
csvOutput.write("\"");

And you need to do this because if there is a comma within a data it would cause a problem while parsing and cause data to be lodged in a different columns. Also make sure inside finally block

并且您需要这样做,因为如果数据中有逗号,它会在解析时导致问题并导致数据存放在不同的列中。还要确保在 finally 块内

finally {
//csvOutput is closed here

}