Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android——數據存儲(四種方式之二)讀寫SD卡——練習

Android——數據存儲(四種方式之二)讀寫SD卡——練習

編輯:關於Android編程

\

1保存到SDK ——字符串方式

 

package com.example.jreduch08.SDK;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jreduch08.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class SdActivity extends AppCompatActivity {
private CheckBox c1,c2,c3,c4,c5,c6;
    private Button bt0, bt1,bt2;
    private TextView tv3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);
        getSupportActionBar().hide();

        c1= (CheckBox) findViewById(R.id.c1);
        c2= (CheckBox) findViewById(R.id.c2);
        c3= (CheckBox) findViewById(R.id.c3);
        c4= (CheckBox) findViewById(R.id.c4);
        c5= (CheckBox) findViewById(R.id.c5);
        c6= (CheckBox) findViewById(R.id.c6);

        bt0= (Button) findViewById(R.id.bt0);
        bt1= (Button) findViewById(R.id.bt1);
        bt2= (Button) findViewById(R.id.bt2);
        tv3= (TextView) findViewById(R.id.tv3);

        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder=new AlertDialog.Builder(SdActivity.this);
                builder.setTitle("字體大小請選擇");
                builder.setIcon(R.mipmap.ic_launcher);
                final String[] items={"大","中","小"};
                // builder.setMultiChoiceItems()多選
                builder.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        Toast.makeText(getBaseContext(), items[i].toString(), Toast.LENGTH_SHORT).show();
                        tv3.setText(items[i].toString());
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(false);
                AlertDialog alertDialog=builder.create();
                alertDialog.show();
            }
        });



        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveFile();
            }
        });
        bt0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent=new Intent(SdActivity.this,ShowActivity.class);
                startActivity(intent);

            }
        });


    }


    //保存文件到SD卡
    public  void saveFile(){
        FileOutputStream fos=null;


        //獲取SD卡狀態
        String state= Environment.getExternalStorageState();
        //判斷SD卡是否就緒
        if(!state.equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this,"請檢查SD卡",Toast.LENGTH_SHORT).show();
            return;
        }
        //取得SD卡根目錄
        File file= Environment.getExternalStorageDirectory();

        try {
            Log.d("=====SD卡根目錄:",file.getCanonicalPath().toString());
//            File myFile=new File(file.getCanonicalPath()+"/sd.txt");
//            fos=new FileOutputStream(myFile);
            //輸出流的構造參數1可以是 File對象  也可以是文件路徑
            //輸出流的構造參數2:默認為False=>覆蓋內容;ture=》追加內容
            //追加  ,ture
            fos=new FileOutputStream(file.getCanonicalPath()+"/sd.txt");
            String  str="列表是否顯示摘要:"+c1.isChecked()+":字體大小:"+tv3.getText().toString()
                    +":推送通知:"+c2.isChecked()+":互動插件:"+c3.isChecked()
                    +":自動優化閱讀:"+c4.isChecked()+":收藏時轉發:"+c5.isChecked()
                    +":頂踩時轉發:"+c6.isChecked();
            fos.write(str.getBytes());
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        String str=readFile();
        String  str1[]=str.split(":");
         c1.setChecked(Boolean.parseBoolean(str1[1]));
        c2.setChecked(Boolean.parseBoolean(str1[5]));
        c3.setChecked(Boolean.parseBoolean(str1[7]));
        c4.setChecked(Boolean.parseBoolean(str1[9]));
        c5.setChecked(Boolean.parseBoolean(str1[11]));
        c6.setChecked(Boolean.parseBoolean(str1[13]));
    }
    //從SD卡讀取文件
    public String  readFile(){

        BufferedReader reader=null;

        FileInputStream fis=null;
        StringBuilder sbd=new StringBuilder();

        String statu= Environment.getExternalStorageState();
        if (!statu.equals(Environment.MEDIA_MOUNTED)){

            Toast.makeText(this,"SD卡未就緒",Toast.LENGTH_SHORT).show();
            return  "";
        }
        File root=Environment.getExternalStorageDirectory();
        try {
            fis=new FileInputStream(root+"/sd.txt");
            reader= new BufferedReader(new InputStreamReader(fis));
            String row="";
            try {
                while ((row=reader.readLine())!=null){

                    sbd.append(row);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();

            e.printStackTrace();
        }finally {
            if (reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  sbd.toString();
    }

}
</strong></span>



package com.example.jreduch08.SDK;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jreduch08.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class ShowActivity extends AppCompatActivity {
    private TextView show;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        show= (TextView) findViewById(R.id.show);
        show.setText(readFile());


    }
    //從SD卡讀取文件
    public String  readFile(){

        BufferedReader reader=null;

        FileInputStream fis=null;
        StringBuilder sbd=new StringBuilder();

        String statu= Environment.getExternalStorageState();
        if (!statu.equals(Environment.MEDIA_MOUNTED)){

            Toast.makeText(this,"SD卡未就緒",Toast.LENGTH_SHORT).show();
            return  "";
        }
        File root=Environment.getExternalStorageDirectory();
        try {
            fis=new FileInputStream(root+"/sd.txt");
            reader= new BufferedReader(new InputStreamReader(fis));
            String row="";
            try {
                while ((row=reader.readLine())!=null){

                    sbd.append(row);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();

            e.printStackTrace();
        }finally {
            if (reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  sbd.toString();
    }

}



    

\

 

\

\

 

保存到SDK——對象 類
 

package com.example.jreduch08.entity;

import java.io.Serializable;

/**
 * Created by 沖天之峰 on 2016/8/16.
 */
public class Settings  implements Serializable {
    private boolean  c1;
    private boolean  c2;
    private boolean  c3;
    private boolean  c4;
    private boolean  c5;
    private boolean  c6;
    private String  textsize;

    public Settings(String textsize, boolean c6, boolean c5, boolean c4, boolean c3, boolean c2, boolean c1) {
        this.textsize = textsize;
        this.c6 = c6;
        this.c5 = c5;
        this.c4 = c4;
        this.c3 = c3;
        this.c2 = c2;
        this.c1 = c1;
    }

    public boolean isC1() {
        return c1;
    }

    public void setC1(boolean c1) {
        this.c1 = c1;
    }

    public boolean isC2() {
        return c2;
    }

    public void setC2(boolean c2) {
        this.c2 = c2;
    }

    public boolean isC3() {
        return c3;
    }

    public void setC3(boolean c3) {
        this.c3 = c3;
    }

    public boolean isC4() {
        return c4;
    }

    public void setC4(boolean c4) {
        this.c4 = c4;
    }

    public boolean isC5() {
        return c5;
    }

    public void setC5(boolean c5) {
        this.c5 = c5;
    }

    public boolean isC6() {
        return c6;
    }

    public void setC6(boolean c6) {
        this.c6 = c6;
    }

    public String getTextsize() {
        return textsize;
    }

    public void setTextsize(String textsize) {
        this.textsize = textsize;
    }

    public Settings() {

    }


}

package com.example.jreduch08.entity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jreduch08.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

public class DuixActivity extends AppCompatActivity {
    private CheckBox c1, c2, c3, c4, c5, c6;
    private Button bt0, bt1, bt2;
    private TextView tv3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_duix);
        getSupportActionBar().hide();

        c1 = (CheckBox) findViewById(R.id.c1);
        c2 = (CheckBox) findViewById(R.id.c2);
        c3 = (CheckBox) findViewById(R.id.c3);
        c4 = (CheckBox) findViewById(R.id.c4);
        c5 = (CheckBox) findViewById(R.id.c5);
        c6 = (CheckBox) findViewById(R.id.c6);

        bt0 = (Button) findViewById(R.id.bt0);
        bt1 = (Button) findViewById(R.id.bt1);
        bt2 = (Button) findViewById(R.id.bt2);
        tv3 = (TextView) findViewById(R.id.tv3);

        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(DuixActivity.this);
                builder.setTitle("字體大小請選擇");
                builder.setIcon(R.mipmap.ic_launcher);
                final String[] items = {"大", "中", "小"};
                // builder.setMultiChoiceItems()多選
                builder.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        Toast.makeText(getBaseContext(), items[i].toString(), Toast.LENGTH_SHORT).show();
                        tv3.setText(items[i].toString());
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(false);
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });


        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Settings sets = new Settings();
                sets.setC1(c1.isChecked());
                sets.setC2(c2.isChecked());
                sets.setC3(c3.isChecked());
                sets.setC4(c4.isChecked());
                sets.setC5(c5.isChecked());
                sets.setC6(c6.isChecked());
                sets.setTextsize(tv3.getText().toString());

                String state = Environment.getExternalStorageState();
                if (!state.equals(Environment.MEDIA_MOUNTED)) {
                    Toast.makeText(getBaseContext(), "請檢查SD卡", Toast.LENGTH_SHORT).show();
                    return;
                }
                File root = Environment.getExternalStorageDirectory();
                FileOutputStream fos = null;
                ObjectOutputStream oos = null;
                try {
                    fos = new FileOutputStream(root + "/ttings.txt");
                    oos = new ObjectOutputStream(fos);
                    oos.writeObject(sets);
                    Toast.makeText(getBaseContext(), "保存成功", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (oos != null) {
                        try {
                            oos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }


            }
        });
     bt0.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             Intent intent=new Intent(DuixActivity.this,Show1Activity.class);
             startActivity(intent);

         }
     });





    }

    @Override
    protected void onStart() {
        super.onStart();
        readSettings();
    }

    public void readSettings() {
        File root = Environment.getExternalStorageDirectory();
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(root+ "/ttings.txt");
            ois = new ObjectInputStream(fis);
            Settings sets = (Settings) ois.readObject();
            tv3.setText(sets.getTextsize());
            c1.setChecked(sets.isC1());
            c2.setChecked(sets.isC2());
            c3.setChecked(sets.isC3());
            c4.setChecked(sets.isC4());
            c5.setChecked(sets.isC5());
            c6.setChecked(sets.isC6());



        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}



    
package com.example.jreduch08.entity;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.example.jreduch08.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;

public class Show1Activity extends AppCompatActivity {
    private TextView show;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show1);


        show= (TextView) findViewById(R.id.show);

        readSettings();
    }

    public void readSettings() {
        File root = Environment.getExternalStorageDirectory();
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(root+ "/ttings.txt");
            ois = new ObjectInputStream(fis);
            Settings sets = (Settings) ois.readObject();
            show.setText(sets.getTextsize()+sets.isC1()+sets.isC2()+sets.isC3()+sets.isC4()

            +sets.isC5()+sets.isC6());


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}



    


\\

 


內存儲——SharePreference
 

package com.example.jreduch08.Sharepreferences;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jreduch08.R;

public class SharePreferenceZyfActivity extends AppCompatActivity {
    private CheckBox c1,c2,c3,c4,c5,c6;
    private Button bt0, bt1,bt2;
    private TextView tv3,show;
    private SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_preference_zyf);
        getSupportActionBar().hide();

        c1= (CheckBox) findViewById(R.id.c1);
        c2= (CheckBox) findViewById(R.id.c2);
        c3= (CheckBox) findViewById(R.id.c3);
        c4= (CheckBox) findViewById(R.id.c4);
        c5= (CheckBox) findViewById(R.id.c5);
        c6= (CheckBox) findViewById(R.id.c6);

        bt0= (Button) findViewById(R.id.bt0);
        bt1= (Button) findViewById(R.id.bt1);
        bt2= (Button) findViewById(R.id.bt2);
        tv3= (TextView) findViewById(R.id.tv3);
        show= (TextView) findViewById(R.id.show);
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder=new AlertDialog.Builder(SharePreferenceZyfActivity.this);
                builder.setTitle("字體大小請選擇");
                builder.setIcon(R.mipmap.ic_launcher);
                final String[] items={"大","中","小"};
                // builder.setMultiChoiceItems()多選
                builder.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        Toast.makeText(getBaseContext(), items[i].toString(), Toast.LENGTH_SHORT).show();
                        tv3.setText(items[i].toString());
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(false);
                AlertDialog alertDialog=builder.create();
                alertDialog.show();
            }
        });


        //讀取 SharePreference

        sp=getSharedPreferences("userInfo",MODE_PRIVATE);

      bt1.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              //保存數據到SharePreference
              SharedPreferences.Editor editor=sp.edit();
              editor.putString("text",tv3.getText().toString());
              editor.putBoolean("cc1",c1.isChecked());
              editor.putBoolean("cc2",c2.isChecked());
              editor.putBoolean("cc3",c3.isChecked());
              editor.putBoolean("cc4",c4.isChecked());
              editor.putBoolean("cc5",c5.isChecked());
              editor.putBoolean("cc6",c6.isChecked());
              editor.commit();



          }
      });

    }
    public  void setSettings(){
        Boolean ccc1=sp.getBoolean("cc1",false);
        Boolean ccc2=sp.getBoolean("cc2",false);
        Boolean ccc3=sp.getBoolean("cc3",false);
        Boolean ccc4=sp.getBoolean("cc4",false);
        Boolean ccc5=sp.getBoolean("cc5",false);
        Boolean ccc6=sp.getBoolean("cc6",false);
        String   text1=sp.getString("text","中");
        c1.setChecked(ccc1);
        c2.setChecked(ccc2);
        c3.setChecked(ccc3);
        c4.setChecked(ccc4);
        c5.setChecked(ccc5);
        c6.setChecked(ccc6);
        tv3.setText(text1);
    }

    @Override
    protected void onStart() {
        super.onStart();
        setSettings();
    }
}

\

 

解析JSON

 

//json對應json數據中的{ } 大括號
JSONObject  obj=new JSONObject(sbd.toString());
//json數值對應json數據中的【】 中括號
JSONArray ja=obj.getJSONArray("data");
package com.example.jreduch08;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class PaserJsonActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paser_json);
        StringBuilder sbd=new StringBuilder();
        BufferedReader reader=null;
        InputStream is=null;
        try {
            is=getResources().getAssets().open("cityinfo2.txt");
            reader=new BufferedReader(new InputStreamReader(is));
            String row="";
            while ((row=reader.readLine())!=null){
                sbd.append(row);
             //   sbd.append("\n");
            }
            try {

                //json對應json數據中的{ } 大括號
                JSONObject  obj=new JSONObject(sbd.toString());
                //json數值對應json數據中的【】 中括號
                JSONArray ja=obj.getJSONArray("data");
                for (int i=0;i<ja.length();i++){ jsonobject="" jo="(JSONObject)" ja.get(i);="" if="" (jo.has("name")){="" string="" name="jo.getString(&quot;name&quot;);" log.d("="===&quot;,name);" }="" catch="" (jsonexception="" e)="" {="" e.printstacktrace();="" (ioexception="" }finally="" (reader!="null){" try="" reader.close();="" 
\
package com.example.jreduch08.Sharepreferences;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.example.jreduch08.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class PaserJson2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paser_json2);
        StringBuilder sbd=new StringBuilder();
        BufferedReader reader=null;
        InputStream is=null;
        try {
            is=getResources().getAssets().open("jsonNews.txt");
            reader=new BufferedReader(new InputStreamReader(is));
            String row="";
            while ((row=reader.readLine())!=null){
                sbd.append(row);
                //   sbd.append("\n");
            }
            try {


                //json對應json數據中的{ } 大括號
                JSONObject obj = new JSONObject(sbd.toString());
                //json數值對應json數據中的【】 中括號
                JSONObject ja = obj.getJSONObject("showapi_res_body");
                JSONObject ja1 = ja.getJSONObject("pagebean");
                JSONArray ja2 = ja1.getJSONArray("contentlist");
                for (int k = 0; k < ja2.length(); k++) {
                    JSONObject jo = (JSONObject) ja2.get(k);
                    if (jo.has("content")) {
                        String content = jo.getString("content");
                        Log.d("====", content);

                    }

                }


            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }


    }
}

\

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved