首页 文章

如何使用Java将CSV的空单元格替换为NULL

提问于
浏览
0

我输入了CSV . 其中一列在单元格中没有任何 Value . 在将数据写入另一个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();

        }


    }

1 回答

  • 1

    这是不可能的,csv中的空字符串和空字符串之间没有区别 .

相关问题