【问题标题】:java application that converts CSV to Json将 CSV 转换为 Json 的 java 应用程序
【发布时间】:2014-03-13 15:17:42
【问题描述】:

我正在尝试创建一个 Java 应用程序来将 Excel/csv 文件内容转换为 JSON 格式, 因为我所有的输出 json 文件都有相同的标题。我选择使用带有 BufferedReader 和 BufferedWriter 的经典方法来简化。这是我的代码的一部分:

BufferedReader csvFile= new BufferedReader(new FileReader("DataTextCsv.csv"));
BufferedWriter jsonFile=new BufferedWriter(new FileWriter("converted.txt"));

String fileContent = csvFile.readLine();

// set the constant header 
String jsonScript="constant header of json content";

while (fileContent !=null){
    fileContent=csvFile.readLine();
    String[] tab = fileContent.split(",");
    // variable content from csv file
    jsonScript+="\""+tab[0]+"\" :";
    jsonScript+=tab[1]+","+"\n";

    // End of json content construction
    jsonScript=jsonScript.substring(0,jsonScript.length()-2);
    jsonScript+="}";

    String[] tabWrite=jsonScript.split("\n");
    for (String item:tabWrite){
        jsonFile.write(item);
        jsonFile.newLine(); 
    }
    csvFile.close();
    jsonFile.close();
}

应用程序可以正确读取 csv 文件的第一行,但无法继续到最后,并且我不断收到此错误(即使我尝试将所有 csv 数据设置在一行中:

Exception in thread "main" java.io.IOException: Stream closed
    at java.io.BufferedReader.ensureOpen(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at java.io.BufferedReader.readLine(Unknown Source)
    at CSVConverter.main(CSVConverter.java:17)

我意识到使用更具体的库会更简单,但由于我是 Java 新手,我无法找到合适的包来下载和安装

【问题讨论】:

  • 如果您使用的是 Java 7,请删除文件 API 并使用 Files(以及 try-with-resource 语句)
  • 请注意用逗号分隔。如果某些项目在单元格内容中本身有逗号,则会产生不良结果。改用 supercsv。我的 2c
  • 我的 Excel 文件中的小数点分隔符是“.”
  • 这将在最后一行失败。它将在文档的最后一行输入 while 语句,但会将 fileContent 设置为 null 并在文件末尾中断

标签: java json csv


【解决方案1】:

close 语句移出while 循环(最好移到finally 块中)

csvFile.close();
jsonFile.close();

【讨论】:

  • 谢谢,确实很简单,除了你的建议之外,我还把写作过程从循环中解了出来,重新设置了拆分顺序
【解决方案2】:

请参阅以下内容,您的关闭方法位于错误的位置。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NewClass {

    public static void main(String[] args) {
        BufferedReader csvFile = null;
        BufferedWriter jsonFile = null;
        try {
            csvFile = new BufferedReader(new FileReader("DataTextCsv.csv"));
            jsonFile = new BufferedWriter(new FileWriter("converted.txt"));
            String fileContent = csvFile.readLine();
            // set the constant header
            String jsonScript = "constant header of json content";
            while (fileContent != null) {
                fileContent = csvFile.readLine();
                String[] tab = fileContent.split(",");
                // variable content from csv file
                jsonScript += "\"" + tab[0] + "\" :";
                jsonScript += tab[1] + "," + "\n";
                // End of json content construction
                jsonScript = jsonScript.substring(0, jsonScript.length() - 2);
                jsonScript += "}";
                String[] tabWrite = jsonScript.split("\n");
                for (String item : tabWrite) {
                    jsonFile.write(item);
                    jsonFile.newLine();
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                csvFile.close();
                jsonFile.close();
            } catch (IOException ex) {
                Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

或者选项二使用try-with资源

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

   public class NewClass {
    public static void main(String[] args) {
        try (BufferedReader csvFile = new BufferedReader(new FileReader("DataTextCsv.csv")); BufferedWriter jsonFile = new BufferedWriter(new FileWriter("converted.txt"))) {
            String fileContent = csvFile.readLine();
            // set the constant header
            String jsonScript = "constant header of json content";
            while (fileContent != null) {
                fileContent = csvFile.readLine();
                String[] tab = fileContent.split(",");
                // variable content from csv file
                jsonScript += "\"" + tab[0] + "\" :";
                jsonScript += tab[1] + "," + "\n";
                // End of json content construction
                jsonScript = jsonScript.substring(0, jsonScript.length() - 2);
                jsonScript += "}";
                String[] tabWrite = jsonScript.split("\n");
                for (String item : tabWrite) {
                    jsonFile.write(item);
                    jsonFile.newLine();
                }
            }
            csvFile.close();
            jsonFile.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

【讨论】:

    【解决方案3】:

    您需要在 while 循环中为 null 值添加另一个捕获。另外,我不确定您是否打算像现在一样重复所有行。这种方式只返回最后一行/完整的数据集

                while (fileContent !=null){
                      fileContent=csvFile.readLine();
                      if (fileContent != null){
                          String[] tab = fileContent.split(",");
                          // variable content from csv file
                          jsonScript+="\""+tab[0]+"\" :";
                          jsonScript+=tab[1]+","+"\n";
    
                          // End of json content construction
                          jsonScript=jsonScript.substring(0,jsonScript.length()-2);
                          jsonScript+="}";
                      }else{
                          String[] tabWrite=jsonScript.split("\n");
                          for (String item:tabWrite){
                              result.append(item);
                              jsonFile.write(item);
                              jsonFile.newLine(); 
                          }
    
                      }
                  }
                  csvFile.close();
                  jsonFile.close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 2020-06-24
      • 1970-01-01
      • 2018-12-04
      • 2017-05-28
      相关资源
      最近更新 更多