我有一个包含70个对象的JSON文件,每个对象都包含数组等元素。以下是JSON对象的示例:
{
"journal": ".....",
"category": ["Sport", "football", "Real Madrid"],
"abstract": "Here is an example"
}
首先,我使用元素"category"
的Strings创建文件夹。下一步是根据元素"abstract"
的字符串创建一个.txt
文件。我想做的是将每个.txt
文件保存在这些文件夹中。
例如,元素"abstract"
包含字符串"Here is an example",我用这个短语创建了一个.txt
文件,我想知道如何将其保存在文件夹Sport
、Football
和Real Madrid
中。
下面是一些示例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.
}
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);
}