Maya
Maya

Reputation: 67

java application that converts CSV to Json

I'm trying to create a Java application to convert Excel/csv file content to JSON format, As all my output json files have the same header. I chose to simplify by using a classic method with BufferedReader and BufferedWriter. Here is a portion of my code:

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();
}

The application can correctly read the first line of the csv file but can not continue till the end and I continuously get this error (even if I try to set all my csv data in one line:

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)

I'm conscious that it would be simpler to use more specific libraries, but as I'm new with Java, I wasn't able to find the right package to download and install

Upvotes: 2

Views: 2484

Answers (3)

IbrahimMitko
IbrahimMitko

Reputation: 1207

You need to add another catch for a null value in the while loop. Also I'm not sure if you intended to have all the lines repeated as the are now. This way returns only the last line/full set of data

            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();

Upvotes: 0

Dan Ciborowski - MSFT
Dan Ciborowski - MSFT

Reputation: 7207

See the following, you had your close methods in the wrong location.

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);
            }
        }
    }
}

Or option two using try-with resource

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);
        }
    }
}

Upvotes: 2

Reimeus
Reimeus

Reputation: 159754

Move the close statements out of the while loop (preferably into a finally block)

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

Upvotes: 2

Related Questions