Я пытаюсь создать приложение 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, я не смог найти нужный пакет для загрузки и установки
Перемещение close
заявлений выхода из в while
цикла (предпочтительно в finally
блок)
csvFile.close();
jsonFile.close();
Вам нужно добавить еще один catch для null
значения в цикле while. Также я не уверен, что вы намереваетесь повторить все строки, как сейчас. Этот способ возвращает только последнюю строку/полный набор данных
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();
См. Следующее: у вас были близкие методы в неправильном месте.
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 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);
}
}
}