【问题标题】:How to replace empty cell of a CSV with text as NULL using Java如何使用 Java 将 CSV 的空单元格替换为 NULL 文本
【发布时间】:2018-12-08 19:11:37
【问题描述】:

我输入了 CSV。其中一列在单元格中没有值。在将数据写入另一个 CSV 时,我想在那个空单元格中写入 NULL。 我试图用 NULL 替换 "" 但它在所有单元格中打印 NULL。 此外,我想排除在代码的硬编码列中添加 NULL 文本,即 UniqueId、IsDelete、Rootpid。我希望它们是空的。

到目前为止,这是我的代码:

public static void main(String[] args) throws FileNotFoundException, IOException
    {


        String sourceFilePath = "C://MyData/Emp_Input.csv";
        String newFilePath = "C://MyData/Emp_Output.csv";
        File sourceCsvFile = new File(sourceFilePath);
        File finalCsvFile = new File(newFilePath);
        final Charset Encoding = Charset.forName("UTF-8"); 
        String cvsSplitBy = ",";


        String line = "";

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(finalCsvFile), Encoding));


        try (BufferedReader br = new BufferedReader(new FileReader(sourceCsvFile))) 
        {
            line = br.readLine(); 
            String newFileLine = "UniqueID" + cvsSplitBy +line + cvsSplitBy  + "IsDelete" + cvsSplitBy + "Rootpid";
            writer.write(newFileLine);   
            writer.newLine();


            while ((line = br.readLine()) != null)  
            {   
            /*  if (line.contains("") )
                {

                    line = line.replace("", "NULL"); // missing code to replace empty cell of a csv with text as NULL
                } */


                else if (line.contains("TRUE") || line.contains("FALSE"))
                {
                    line = line.replace("TRUE", "1");
                    line = line.replace("FALSE", "0");

                } 


                    newFileLine =  cvsSplitBy + line + cvsSplitBy + cvsSplitBy;
                    writer.write(newFileLine);  
                    writer.newLine();


            }

            writer.close();

        }


    }

【问题讨论】:

    标签: java csv


    【解决方案1】:

    不可能,csv中的空字符串和空字符串没有区别。

    【讨论】:

    • 同意!但是我需要进一步处理应用程序,我希望将 NULL 作为文本写入那些为空的单元格中。
    • 你可以配置excel在你的csv中为空字符串显示NULL,但是如果你在cvs中写null,它的值“null”当然不同于空对象和空对象
    • 是的,我希望将 null 值写入 CSV。
    猜你喜欢
    • 2017-03-31
    • 2016-11-07
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    相关资源
    最近更新 更多