我想将大型JSON
数组数据存储到 CSV 文件中。我怎样才能做到这一点?
我有以下代码,它不会将任何数据保存到在我的 android“test”文件夹中创建的“test1.csv”文件中。
这是代码。
JSONArray outerArray = [{"value":true,"Id":0,"name":"214"}, {"value":true,"Id":0,"name":"215"},{"value":true,"Id":0,"name":"216"}]
public void saveCsv(JSONArray outerArray) throws IOException, JSONException {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/test/";
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdir();
}
File file;
EditText editText = (EditText) findViewById(R.id.editText1);
if (!editText.getText().toString().equals("")) {
file = new File(rootPath, editText.getText().toString() + ".csv");
} else {
editText.setError("Defualt csv file name will be used");
Toast.makeText(this, "CSV name is empty", 5000).show();
file = new File(rootPath, "test1.csv");
}
file.createNewFile();
if (file.exists()) {
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
String[][] arrayOfArrays = new String[outerArray.length()][];
for (int i = 0; i < outerArray.length(); i++) {
JSONObject innerJsonArray = (JSONObject) outerArray.get(i);
String[] stringArray1 = new String[innerJsonArray.length()];
for (int j = 0; j < innerJsonArray.length(); j++) {
stringArray1[j] = (String) innerJsonArray.get("value");
}
arrayOfArrays[i] = stringArray1;
writer.writeNext(arrayOfArrays[i]);
}
writer.close();
}
}