如何在多个文件夹中保存字符串json元素

polhcujo  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(322)

我有一个包含70个对象的json文件,每个对象都包含数组等元素。以下是json对象的示例:

{ 
   "journal": ".....",
   "category": ["Sport", "football", "Real Madrid"],
   "abstract": "Here is an example"
}

首先,我用元素的字符串创建文件夹 "category" . 下一步是创建 .txt 从元素的字符串 "abstract" . 我要做的就是保存每一个 .txt 这些文件夹上的文件。
例如,元素 "abstract" 包含字符串“这里是一个例子”,我创建一个 .txt 用这个短语归档,我想知道如何将它保存在文件夹中 Sport , Football 以及 Real Madrid .

jgzswidk

jgzswidk1#

下面是一些java示例:

// create a list of folder names and call it "folderArray".
// You are already doing something like this, but I don't know the variable name.
// You also have the name of the abstract text file name in a variable.
// This code assumes that variable is called "abstractFileName".

for (final String folder : folderArray)
{
    final String newFileName = folder + File.separatorChar + abstractFileName;

    // create a file with the name "newFileName"

    // Write the abstract contents to the new file.
}
qf9go6mv

qf9go6mv2#

JSONObject obj = new JSONObject(jsonString);
JSONArray arr = obj.getJSONArray("category");
File f = new File("C:/Files");
for(int i = 0; i < arr.length; i++)
{
  String folderName = arr.getString(i);
  File folder = new File(folderName);
  if(folder.mkdir()) {
    File file = new File(folderName + "fileName.txt");
    String data = obj.getString("abstract");

    // Now using stream write the data to this file
    DataOutputStream dos = new DataOutputStream(FileOutputStream(file));
    dos.writeUTF(data);
}

相关问题