Android——数据存储(四种方式)
1.SharedPrefereces 只能保存一些简单的数轻量级.XML 存储文件名,
数据保存在data/data/basepackage/shared_prefs/myopt.xml中
实例-收藏-记住密码自动登录
//一种轻量级的数据存储方式//通过KEY
存入数据——putxxxx(key,value)
取出数据——getxxxx(key default)
2.读写SD卡 SD的根目录 适用于数据流读写
实现步骤:加入读写SD卡权限
判断SD卡是否存在
读写文件
3.SQLite 轻量级 .dp文件多用于手机里
4.Content prowvider内容提供者
网路存储 在网络后台存储
1保存文件内存储
package com.example.jreduch08;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class InnerIoActivity extends AppCompatActivity {
private EditText content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_io);
Button save= (Button) findViewById(R.id.save);
Button read= (Button) findViewById(R.id.read);
Button delete= (Button) findViewById(R.id.delete);
final TextView show= (TextView) findViewById(R.id.show);
content= (EditText) findViewById(R.id.content);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveFile();
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
show.setText( readFile());
}
});
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
removeFile();
}
});
}
//保存文件内存储
public void saveFile(){
FileOutputStream fos=null;
/*MODE_APPEND 追加 MODE_PRIVATE 覆盖
//OpenFileoutput返回一个 输出字节流
//指向的路径为data/data/包名/file/
//参数1.文件名称(如果不存在则自动创建)
参数2.模式MODE_APPEND 文件内容追加
MODE_PRIVATE 文件内容被覆盖
*/
try {
fos= openFileOutput("text.txt",MODE_APPEND);
String str=content.getText().toString();
try {
fos.write(str.getBytes());
Toast.makeText(InnerIoActivity.this,"保存成功",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fos!=null){
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//从内存读文件
public String readFile(){
StringBuilder sbd=new StringBuilder();
BufferedReader reader=null;
FileInputStream fis=null;
try {
fis=openFileInput("text.txt");
reader=new BufferedReader(new InputStreamReader(fis));
try {
sbd.append(getFilesDir().getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
String row="";
try {
while ((row=reader.readLine())!=null){
sbd.append(row);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(),"文件不存在",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sbd.toString();
}
//删除文件
public void removeFile(){
String[] files=fileList();
for (String str:files){
// Log.d("=====",str);
if (str.equals("text.txt")){
deleteFile("text.txt");}
}
}
}
2保存文件到SD卡
从SD卡读取文件
package com.example.jreduch08;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
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 SaveToSdCarActivity extends AppCompatActivity {
private Button save,read,delete;
private EditText content;
private TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_io);
save= (Button) findViewById(R.id.save);
read= (Button) findViewById(R.id.read);
delete= (Button) findViewById(R.id.delete);
content= (EditText) findViewById(R.id.content);
show= (TextView) findViewById(R.id.show);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveFile();
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
show.setText(readFile());
}
});
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
removeFile();
}
});
}
//保存文件到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",true);
String str=content.getText().toString();
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();
}
}
}
}
//从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();
}
//删除SD卡文件
public void removeFile(){
String statu=Environment.getExternalStorageState();
if (!statu.equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();
return;
}
File root=Environment.getExternalStorageDirectory();
// File sd=new File(root,"sd.txt");
File sd=new File(root+"/sd.txt");
if(sd.exists()){
sd.delete();
Toast.makeText(this,"文件删除成功",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
}
}
}
3读取assets目录 读取raw文件夹
package com.example.jreduch08;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ReadRawAssetsActivity extends AppCompatActivity {
private Button raw,assets;
private TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_raw_assets);
raw=(Button)findViewById(R.id.raw);
assets= (Button) findViewById(R.id.assets);
show= (TextView) findViewById(R.id.show);
raw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
show.setText(readRaw());
}
});
assets.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
show.setText(readAssets());
}
});
}
//读取assets目录
public String readAssets(){
StringBuilder sbd=new StringBuilder();
BufferedReader reader=null;
InputStream is=null;
try {
is=getResources().getAssets().open("cityinfo");
reader=new BufferedReader(new InputStreamReader(is));
String row="";
while ((row=reader.readLine())!=null){
sbd.append(row);
sbd.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sbd.toString();
}
//读取raw文件夹
public String readRaw(){
StringBuilder sbd=new StringBuilder();
BufferedReader reader=null;
InputStream is=null;
is=getResources().openRawResource(R.raw.settings);
reader=new BufferedReader(new InputStreamReader(is));
String row="";
try {
while ((row=reader.readLine())!=null){
sbd.append(row);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sbd.toString();
}
}
4
将图片保存到SD卡
从SD卡读取图片
从网络获取图片
从网络获取图片直接保存
package com.example.jreduch08;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ViewPagerSdActivity extends AppCompatActivity {
private ImageView img1,img2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pager_sd);
img1= (ImageView) findViewById(R.id.img1);
img2= (ImageView) findViewById(R.id.img2);
}
//从网络获取图片直接保存
public void SaveHttp(View view){
new SaveHttpImg().execute("http://p2.so.qhmsg.com/t0165453974dc3b9af7.jpg");
}
//从网络获取图片
public void GetUrlImg(View view){
new GetImg().execute("http://p1.so.qhmsg.com/dm/365_365_/t01df531d143d2554d7.jpg");
}
//保存网络图片
public void SaveUrlImg(View view){
new Get2Img().execute("http://p1.so.qhmsg.com/dm/365_365_/t01df531d143d2554d7.jpg");
}
//从SD卡读取图片
public void rawImg(View view){
String path=Environment.getExternalStorageDirectory()+"/1.png";
//方法一 根据URI加载数据图片
// img2.setImageURI(Uri.parse(path));
// 方法二:通过BitmapFactory的静态方法decodeFile()
// 参数图片路径
Bitmap bitmap= BitmapFactory.decodeFile(path);
img2.setImageBitmap(bitmap);
/*方法三:通过BitmapFactory的静态方法 decodeStream()
// 参数为 输入流InputStream
try {
BitmapFactory.decodeStream(new FileInputStream(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
*/
}
//将图片保存到SD卡
//布局监听
public void saveImg(View view){
//获取ImageView中的图片
BitmapDrawable bitmapDrawable=(BitmapDrawable)
img1.getDrawable();
Bitmap bitmap=bitmapDrawable.getBitmap();
String statu= Environment.getExternalStorageState();
if (!statu.equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();
return;
}
/*
通过 Bitmap(位图)压缩的方法(compress)保存图片到SD卡
参数1:图片格式(PNG,JPEG WEBP)
参数2:图片质量(0-100)
参数3:输出流
*/
File root=Environment.getExternalStorageDirectory();
FileOutputStream fos=null;
try {
fos=new FileOutputStream(root+"/1.png");
bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
Toast.makeText(this,"图片保存成功",Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//网络存储图片
public void save2Img(){
//获取ImageView中的图片
BitmapDrawable bitmapDrawable=(BitmapDrawable)
img2.getDrawable();
Bitmap bitmap=bitmapDrawable.getBitmap();
String statu= Environment.getExternalStorageState();
if (!statu.equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();
return;
}
/*
通过 Bitmap(位图)压缩的方法(compress)保存图片到SD卡
参数1:图片格式(PNG,JPEG WEBP)
参数2:图片质量(0-100)
参数3:输出流
*/
File root=Environment.getExternalStorageDirectory();
FileOutputStream fos=null;
try {
fos=new FileOutputStream(root+"/1.png");
bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
Toast.makeText(this,"图片保存成功",Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class GetImg extends AsyncTask {
//onPreExecute在主线程中执行命令
//进度条的初始化
@Override
protected void onPreExecute() {
super.onPreExecute();
}
//doInBackground在子线程中执行名命令
@Override
protected Bitmap doInBackground(String... strings) {
HttpURLConnection con = null;
InputStream is = null;
Bitmap bitmap = null;
try {
URL url = new URL(strings[0]);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(5 * 1000);
/*
*http相应200:成功
* 404未找到
* 500发生错误
*/
if (con.getResponseCode() == 200) {
is = con.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
if (con != null) {
con.disconnect(); //断开连接
}
}
}
return null;
}
//onPostExecute在UI线程中执行命令 主线程
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
img2.setImageBitmap(bitmap);
}
}
public class Get2Img extends AsyncTask {
//onPreExecute在主线程中执行命令
//进度条的初始化
@Override
protected void onPreExecute() {
super.onPreExecute();
}
//doInBackground在子线程中执行名命令
@Override
protected Bitmap doInBackground(String... strings) {
HttpURLConnection con = null;
InputStream is = null;
Bitmap bitmap = null;
try {
URL url = new URL(strings[0]);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(5 * 1000);
/*
*http相应200:成功
* 404未找到
* 500发生错误
*/
if (con.getResponseCode() == 200) {
is = con.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
if (con != null) {
con.disconnect(); //断开连接
}
}
}
return null;
}
//onPostExecute在UI线程中执行命令 主线程
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
img2.setImageBitmap(bitmap);
save2Img();
}
}
public class SaveHttpImg extends AsyncTask{
@Override
protected String doInBackground(String... strings) {
HttpURLConnection con = null;
InputStream is = null;
try {
URL url = new URL(strings[0]);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5*1000);
con.setReadTimeout(5*1000);
File root = Environment.getExternalStorageDirectory();
FileOutputStream fos = new FileOutputStream(root+"/http.jpg");
if(con.getResponseCode()==200){
is = con.getInputStream();
int next=0;
byte[] bytes = new byte[1024];
while ( (next = is.read(bytes))>0){
fos.write(bytes,0,next);
}
fos.flush();
fos.close();
return root+"/http.jpg";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(con!=null){
con.disconnect();
}
}
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(!s.equals("")){
Toast.makeText(ViewPagerSdActivity.this,"保存路径:"+s,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(ViewPagerSdActivity.this,"保存失败:",Toast.LENGTH_SHORT).show();
}
}
}
}