如何使用下面提到的具体格式写入csv表

时间:2018-05-23 08:44:04

标签: java filewriter

我们需要获得以下格式

Redemption Reference Code|Status|Delivery company|Shipper Tracking Number|Comments
2006995040|Shipped|USPS|ABCD12345|Order SHIPPED
2006995042|Cancelled|||INVALID Address
2006995048|Ordered|USPS|ABCD12345|Order SHIPPED

我正在使用以下代码

private void accumulateOrdersFromPlacement(){
        int count = 0;
        for (int i = 0; i < orderIds.size(); i++) {


            if (count == 0) {
                outPutLineData.add(orderIds.get(i));
                outPutLineData.add("Cancelled");
                outPutLineData.add("");
                outPutLineData.add(" ");
               outPutLineData.add(" ");
                cancelledStatusLineItems.add(orderIds.get(i));
                count++;
            } else if (count == 1) {
                outPutLineData.add(orderIds.get(i));
                outPutLineData.add("Shipped");
                if (outPutLineData.contains("Shipped")) {
                    outPutLineData.add("USPS");
                    outPutLineData.add("order SHIPPED");
                    outPutLineData.add("");
                }
                shippedStatusLineItems.add(orderIds.get(i));
                count++;
            } else if (count == 2) {
                outPutLineData.add(orderIds.get(i));
                outPutLineData.add("No Longer Available");
                outPutLineData.add("");
                outPutLineData.add(" ");
                outPutLineData.add(" ");
                count++;
                nlaStatusLineItems.add(orderIds.get(i));
            } else if (count == 3) {
                outPutLineData.add(orderIds.get(i));
                outPutLineData.add("Ordered");
                outPutLineData.add("");
                outPutLineData.add(" ");
                outPutLineData.add(" ");
                orderedStatusLineItems.add(orderIds.get(i));
                count = 0;
            }
        }

我使用下面的代码创建文件。这是详细的编码。这对于理解代码有更多的可读性。我对代码感到困惑。我们正在接受订单ID计数,并且基于此代码正在运行。

private File createFile(final File directory) {
    FileWriter fw = null;
    File tempFile = null;
    try {
        directory.mkdir();

       tempFile = new File(".//FidelityFulfillment//" + generateFileName(countyThreeLetterCode, "FidelityFulfillment", ".csv", date));
        logReport(GenericConstants.NEW_LINE + "Fulfillment file creating:", tempFile.getName());
        fw = new FileWriter(tempFile, true);
        try (BufferedWriter writer  = new BufferedWriter(new FileWriter(tempFile, true))) {
            writer.write(generateHeaderLine());
            writer.newLine();


           for (int y = 1; y < outPutLineData.size(); y++) {

                if (y % 5 < 4) {  

                     writer.write(outPutLineData.get(y-1) + fieldSeperator);
                     logReport(outPutLineData.get(y - 1) + fieldSeperator);
                }
                else {

                     writer.write(outPutLineData.get(y-1));
                    logReport(outPutLineData.get(y));
                }
                 if (y % 5 == 0) {
                     writer.newLine();
                     logReport("newline");
                 }  
            }



            writer.close();
        } catch (final IOException e) {
            e.printStackTrace();
            final String err = "Unable to write file due to : " + e;
            logReport(GenericConstants.NEW_LINE + "Unable to create temp local File");
        } finally {
            fw.close();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return tempFile;
}

获得回复

Redemption Reference Code|Status|Delivery company|ShipperTrackingNumber|Comments
2006964032|Cancelled|| |
newline
2006964034|Shipped|USPS||
newline
2006964036|No Longer Available||

最后一行pipline正在丢失

1 个答案:

答案 0 :(得分:0)

首先,你以一种奇怪的方式循环:

for (int y = 1; y < outPutLineData.size(); y++) {  

一般来说,我们从0开始。

但你试图用以下条件纠正错误:

if (y % 5 < 4) {  
    //System.out.print("size:"+y);
    writer.write(outPutLineData.get(y-1) + fieldSeperator);
    logReport(outPutLineData.get(y - 1) + fieldSeperator);
}
else {
    //System.out.print("size noseperator:"+y);
    writer.write(outPutLineData.get(y-1));
    logReport(outPutLineData.get(y));
}

相反,只需使用迭代器读取值,然后读取正确的值:

Iterator<String> it = outPutLineData.iterator();
while(it.hasNext()){
    for (int j = 0; j < columnCount; ++j) {
        writer.write(it.next());
        if( j < columnCount - 1)
            writer.write(fieldSeperator);
    }
    writer.newLine();
}

在控制台中打印StringBuilder的示例:

int columnCount = 2;
String fieldSeperator = "|";

List<String> list = Arrays.asList("foo", "1", "bar", "2");
Iterator<String> it = list.iterator();

//Safe guard !
if(list.size() % columnCount != 0)
    throw new RuntimeException("The list does have the correct amount of data");

    while(it.hasNext()){
    for (int j = 0; j < columnCount; ++j) {
        sb.append( it.next() );
        if( j < columnCount - 1)
            sb.append(fieldSeperator );
    }
    System.out.println(sb.toString());
    sb.setLength(0);
}
  

FOO | 1个
  杆| 2

使用POJO

您使用List<String>来保存值,您需要知道需要读取多少列才能获取值。相反,使用POJO:

public class Redemption{
    String redemptionReference;
    String code;
    String status;
    String deliveryCompany;
    String shipperTrackingNumber;
    String comments;
}

在第一个循环中创建实例:

List<Redemption> list...

这样,你只需要迭代每个实例来构建你的行:

for(Redemption r: list){
    writer.write(r.getRedemptionReference() + fieldSeperator);
    ...
    writer.write(r.getComments());
    writer.newLine();
}

当然,你需要使用getter和setter,但这只是为了表明你应该做什么。

CSV API

大警告,编写自己的CSV编写器很危险。如果您有"This is a | character"之类的评论。你最终会得到一条代码:

2006995040|Shipped|USPS|This is a | character|Order SHIPPED

那一列很多......因为你应该有

2006995040|Shipped|USPS|"This is a | character"|Order SHIPPED

但你没有检查那个案子,这只是一个案例。使用CSV API更安全,更简单。

请参阅Any good library to read and write csv files?