如何将json文件从目录移动到另一个目录(缓存目录)

时间:2017-08-13 17:58:46

标签: java android json parsing

我正在尝试创建一个代码,将我的json文件(在assets目录中)移动到缓存目录中,读取文件并解析它。我已经知道如何解析它,但我不知道如何处理缓存目录。但我不知道该怎么做。我是android的新手。任何帮助,将不胜感激。这是代码:在读取资源和解析的过程中,我需要将文件移动到缓存目录中并在那里读取。我怎么能用代码呢?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    List<String> questions = new ArrayList();
    // Reading json file from assets folder
    StringBuffer sb = new StringBuffer();
    BufferedReader br = null;
    String temp="";
    try {
        br = new BufferedReader(new InputStreamReader(getAssets().open("animals.json")));

        while ((temp = br.readLine()) != null)
            sb.append(temp);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close(); // stop reading
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    TextView output = (TextView) findViewById(R.id.textView1);
    String myjsonstring = sb.toString();
    String strJson="";
    String data = "";
    try {
        // Create the root JSONObject from the JSON string.
        JSONObject jsonRootObject = new JSONObject(myjsonstring);

        //Get the instance of JSONArray that contains JSONObjects
        JSONArray jsonArray = jsonRootObject.getJSONArray("Employee");

        //Iterate the jsonArray and print the info of JSONObjects
        for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            String text = jsonObject.optString("text").toString();
            String name = jsonObject.optString("name").toString();
            float salary = Float.parseFloat(jsonObject.optString("salary").toString());

            data += "Data"+i+" : \n text= "+ text +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
        }
       //String cacheDir = context.getCacheDir();
        readAllCachedText(getApplicationContext(),"animals.json");
        //FileInputStream fis = new FileInputStream(new File(getCacheDir(), "cachefile"));
        //String yourFilePath = context.getFilesDir() + "/" + "animals.json";
        //File yourFile = new File( yourFilePath );
        //FileInputStream fis = new FileInputStream(new File(getCacheDir(), "cachefile"));
        output.setText(data);
    } catch (JSONException e) {e.printStackTrace();}
}

0 个答案:

没有答案