简体   繁体   English

使用csvreader在Java中无法正确读取CSV

[英]CSV is not getting read properly in java using csvreader

This is my code. 这是我的代码。 I am not able to write it back to a csv. 我无法将其写回csv。 I have figured out that the problem is with the header matching in the if loop. 我发现问题出在if循环中的标头匹配。 The values are being read correctly nut the if loop is not getting satisfied when the headers are getting matched. 在匹配标头时,如果if循环未得到满足,将正确读取值。 Any help is much appreciated. 任何帮助深表感谢。 Thanks. 谢谢。

public class FactsChecker {
public static void main(String[] args) {

    run();
}


static void run()
{
    Map <String,String> csvMap = new HashMap<String,String>();
    String csvPath = "resource/Sample.csv";
    String outputPath = "resource/Output.csv";
    String[] headers;
    try{
    CsvReader csvreader = new CsvReader("resource/Sample.csv");
    csvreader.readHeaders();
    headers = csvreader.getHeaders();
    String[] values;
    String key = null;
    String value = null;
    while (csvreader.readRecord()){`

        values = csvreader.getValues();
        System.out.println(headers[0]);

        for (int i = 0; i < headers.length; i++) {
            if (headers[i].equals("FCT_NAME")) {
                key = values[i];
            }
            if (headers[i].equals("FCT_TYPE")) {
                value = values[i];
            }
        }




        csvMap.put(key,value);

    }

    for (Map.Entry<String, String> entry : csvMap.entrySet())
    {
        System.out.println(entry.getKey() + "/" + entry.getValue());
    }

Map<String,Entry> entryMap= new HashMap<String, Entry>();
for (String factKey:csvMap.keySet()){
    Entry entry = new Entry();
    entry.setFactName(factKey);
    String factType = csvMap.get(factKey);
    System.out.println(factKey);
    entry.setFactType(factType);
    entryMap.put(factKey, entry);

}

    CsvWriter writer = new CsvWriter(outputPath);
    for(String key1 : entryMap.keySet()){
        Entry entry = entryMap.get(key1);
        writer.writeRecord(new String[]{entry.getFactName(),entry.getFactType()});
    }
    writer.close();

}

    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
}

如果存在尾随空格或前导空格,请尝试使用包含而不是等于

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM