android .向sdcard写入json字符串、读取json字符保存到list<类>中供调用

来源:互联网 发布:python中异常处理 编辑:程序博客网 时间:2024/05/18 03:02

第一.   要向android项目libs文件夹里添加gson-2.2.2.jar文件。

 

Txt文件中的json字符串:

[{"ID":1,"LineColor":-16776961,"FillColor":-16776961,"LineSpan":10,"LineWidth":1,"Display":true,"Selected":true},

 {"ID":2,"LineColor":-16776961,"FillColor":-16776961,"LineSpan":10,"LineWidth":1,"Display":true,"Selected":true},

 {"ID":3,"LineColor":-16776961,"FillColor":-16776961,"LineSpan":10,"LineWidth":1,"Display":true,"Selected":true},

 {"ID":4,"LineColor":-16776961,"FillColor":-16776961,"LineSpan":10,"LineWidth":1,"Display":true,"Selected":true}

]

 

 

主程序中:

开头声明:

List<Styles> userslist;

在读取的按钮事件里:

// 加载样式类列表

      loadStylesList();

 

上边方法的内容为:

publicvoidloadStylesList() {

      if (!checkSDCard()) {

         Toast.makeText(Map.this,"no sdcard",Toast.LENGTH_SHORT).show();

         return;

      }

      ReadWriteStylesrws = newReadWriteStyles(Map.this);

 

      userslist =rws.parseConfigFromJson();

 

      for (int i = 0; i <userslist.size(); i++) {

         Stylesco = userslist.get(i);

         Toast.makeText(this, Integer.toString(co.getID()),

                Toast.LENGTH_LONG).show();

         Toast.makeText(this, co.getName(), Toast.LENGTH_LONG).show();

        

         Toast.makeText(this, Integer.toString(co.getLineColor()),

                Toast.LENGTH_LONG).show();

         Toast.makeText(this, Integer.toString(co.getFillColor()),

                Toast.LENGTH_LONG).show();

         Toast.makeText(this, Integer.toString(co.getLineSpan()),

                Toast.LENGTH_LONG).show();

         Toast.makeText(this, Integer.toString(co.getLineWidth()),

                Toast.LENGTH_LONG).show();

         Toast.makeText(this, Boolean.toString(co.getDisplay()),

                Toast.LENGTH_LONG).show();

         Toast.makeText(this, Boolean.toString(co.getSelected()),

                Toast.LENGTH_LONG).show();

      }

 

   }

 

-====================================

一个读/写json的类:ReadWriteStyles.java:

 

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.IOException;

import java.io.InputStream;

import java.lang.reflect.Type;

import java.util.ArrayList;

import java.util.List;

 

import xm.amgis.common.CompatManager;

import xm.amgis.utiles.Tags;

 

import android.content.Context;

import android.graphics.Color;

import android.os.Environment;

import android.widget.Toast;

 

import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;

 

public class ReadWriteStyles {

 

   StringfileDirectoryString = getSDDir() + "/" + Tags.BASE_DIR

         +Tags.CONFIG_STYLES; // 统一存储路径接口

   StringfileNameString = "styles.txt";

  

   FiledirectoryFile = null;

   FilestyleFile = null;

   FileWriterfw;

   BufferedWriterbw;

   Contextcontext;

 

   publicReadWriteStyles(Context context) {

      this.context= context;

   }

 

   publicList<Styles> parseConfigFromJson() {

      StringfileContent = readAssetsFileString();

      if(fileContent.equals("") || fileContent.length() == 0) {

         returnnull;

      }

      TypelistType = new TypeToken<List<Styles>>() {

      }.getType();

      Gsongson = new Gson();

      List<Styles>styleslist = gson.fromJson(fileContent, listType);

      returnstyleslist;

   }

 

   publicString readAssetsFileString() {

      Stringstr = null;

      try{

         styleFile= new File(fileDirectoryString + fileNameString);

         InputStreaminputStream = null;

          if(!styleFile.exists()){

         writeToFile();

          }

         inputStream= new FileInputStream(styleFile);

         intsize = inputStream.available();

         byte[]buffer = new byte[size];

         inputStream.read(buffer);

         inputStream.close();

         str= new String(buffer);

 

      }catch (IOException e) {

         //TODO Auto-generated catch block

         e.printStackTrace();

      }

      returnstr;

   }

 

   publicvoid writeToFile() {

       if (!checkSDCard()) {

          showMessage("no sdcard");

          return ;

          }

         try{

            directoryFile= new File(fileDirectoryString);

            if(!directoryFile.exists()) {

                directoryFile.mkdirs();

            }

            styleFile= new File(fileDirectoryString + fileNameString);

         }catch (Exception e) {

            //TODO: handle exception

            e.printStackTrace();

         }

       String writeString = createJSONObject();

         try{

            fw= new FileWriter(styleFile);

            bw= new BufferedWriter(fw);// 使用缓冲数据流封装输出流

            bw.write(writeString);

            bw.newLine();

            bw.flush();

            bw.close();

         }catch (IOException e) {

            //TODO Auto-generated catch block

            e.printStackTrace();

         }

      }

 

   // 创建以下的JSON对象,转化为了字符串

   publicString createJSONObject() {

      Gsongson = new Gson();

      Stylescon1 = new Styles();

      con1.setDisplay(true);

      con1.setName("sdcard/ss.txt");

      con1.setFillColor(Color.BLUE);

      con1.setID(1);

      con1.setLineColor(Color.BLUE);

      con1.setLineSpan(10);

      con1.setLineWidth(10);

      con1.setSelected(true);

 

      Stylescon2 = new Styles();

      con2.setDisplay(true);

      con2.setName("sdcard/ss.txt");

      con2.setFillColor(Color.BLUE);

      con2.setID(2);

      con2.setLineColor(Color.BLUE);

      con2.setLineSpan(10);

      con2.setLineWidth(10);

      con2.setSelected(true);

 

      Stylescon3 = new Styles();

      con3.setDisplay(true);

      con3.setName("sdcardsstxt");

      con3.setFillColor(Color.BLUE);

      con3.setID(3);

      con3.setLineColor(Color.BLUE);

      con3.setLineSpan(10);

      con3.setLineWidth(10);

      con3.setSelected(true);

 

      Stylescon4 = new Styles();

      con4.setDisplay(true);

      con4.setName("sdcardsstxt");

      con4.setFillColor(Color.BLUE);

      con4.setID(4);

      con4.setLineColor(Color.BLUE);

      con4.setLineSpan(10);

      con4.setLineWidth(10);

      con4.setSelected(true);

 

      List<Styles>list = new ArrayList<Styles>();

      list.add(con1);

      list.add(con2);

      list.add(con3);

      list.add(con4);

      StringjsonString = gson.toJson(list);

      returnjsonString;

   }

 

   protectedfinal String getSDDir() {

      try{

         StringSD_DIR = CompatManager.getInstance().getRegisteredContext()

                .getExternalStorageDirectoryPath();

         returnSD_DIR;

      }catch (Exception e) {

         return"";

      }

   }

 

   publicboolean checkSDCard() {

      StringsdStatus = Environment.getExternalStorageState();

      if(sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用

         returntrue;

      }else {

         returnfalse;

      }

   }

 

   publicvoid showMessage(String str) {

      Toast.makeText(context,str, Toast.LENGTH_SHORT).show();

   }

}

 

Json字符串对应字段的类:Styles.java:

public class Styles {

         privateint ID;

         privateString Name;

         privateint LineColor;

         privateint FillColor;

         privateint LineSpan;

         privateint LineWidth;

         privateboolean Display;

         privateboolean Selected;

         publicint getID() {

                   returnID;

         }

         publicvoid setID(int ID){

                   this.ID=ID;

         }

        

         publicString getName(){

                   returnName;

         }

         publicvoid setName(String Name){

                   this.Name=Name;

         }

        

         publicint getLineColor(){

                   returnLineColor;

         }

         publicvoid setLineColor(int LineColor){

                   this.LineColor=LineColor;

         }

        

         publicint getFillColor() {

                   returnFillColor;

         }

         publicvoid setFillColor(int FillColor) {

                   this.FillColor=FillColor;

         }

        

         publicint getLineSpan() {

                   returnLineSpan;

         }

         publicvoid setLineSpan(int LineSpan) {

                   this.LineSpan=LineSpan;

         }

        

         publicint getLineWidth(){

                   returnLineWidth;

         }

         publicvoid setLineWidth(int LineWidth){

                   this.LineWidth=LineWidth;

         }

        

         publicboolean getDisplay(){

                   returnDisplay;

         }

         publicvoid setDisplay(boolean Display){

                   this.Display=Display;

         }

        

         publicboolean getSelected() {

                   returnSelected;

         }

         publicvoid setSelected(boolean Selected){

                   this.Selected=Selected;

         }

 

}