【发布时间】:2019-10-02 09:26:06
【问题描述】:
我在 Android 应用程序中将 Json 文件转换为 Csv 格式并将其下载到手机存储中。我通过单击按钮完成所有操作。现在它在手机存储中创建 .csv 文件,但文件为空。我已经调试了应用程序在 for 循环中从 json 获取字符串,但不知道为什么不将其写入 csv 文件。在手机存储中创建的 .csv 文件始终为空。 另外我想给每一行加上标题,我该怎么做。
这是我在编写 csv 时的功能:
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 = null;
file = new File(rootPath, "test4.csv");
if(!file.exists()){
file.createNewFile();
}
if (file.exists()) {
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
for (int i = 0; i < outerArray.length(); i++) {
JSONArray innerJsonArray = (JSONArray) outerArray.getJSONArray(i);
for(int k=0; k<innerJsonArray.length(); k++)
{
String[][] arrayOfArrays = new String[innerJsonArray.length()][];
JSONObject innerJsonObject= (JSONObject) innerJsonArray.getJSONObject(k);
String[] stringArray1 = new String[innerJsonObject.length()];
stringArray1[0]= (String) innerJsonObject.getString("type");
stringArray1[1]= (String) innerJsonObject.getString("title");
stringArray1[2]="";
JSONArray jsonArray= (JSONArray) innerJsonObject.getJSONArray("answer");
for (int j=0; j<jsonArray.length(); j++)
{
stringArray1[2]+=jsonArray.get(j).toString();
stringArray1[2]+=",";
}
arrayOfArrays[k] = stringArray1;
writer.writeNext(arrayOfArrays[k]);
}
}
writer.close();
}
}
【问题讨论】:
-
在此处发布您的 JSONArray
-
我在运行时从 firebase 数据库创建 json
-
任何虚拟格式
-
[[{"answer":["2"],"type":1,"title":"Ques2 radiio"},{"answer":["0","1" ,"3"],"type":3,"title":"Ques3 chk"},{"answer":["简单文本"],"type":2,"title":"Ques1 文本"}, {"answer":["Essay writing"],"type":4,"title":"Ques4 para"}]]
-
它对我有用,你可能没有存储权限