Android---数据读取、存储、删除(内存储/SD卡存储/网络数据读取存储)

本文详细介绍了Android中数据的读取、存储和删除操作,包括内存储的使用,如openFileOutput与deleteFile方法,以及SD卡的读写和删除。同时,还讲解了如何从网络读取并保存图片,涉及Bitmap压缩和Http传输。内容覆盖了存储模式、缓存读取、SD卡权限判断以及异步任务在处理网络数据中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据读取存储之内存储

首先搞清几个概念:
1.数据的存储是以数据流(IO流)的形式进行数据的传递,类似于JAVA中的IO流。
2.存储: openFileOutput 返回一个输出字节流
指向的路径为data/data/包名、files/
参数1:文件名称(如果不存在则自动创建)
参数2:模式:MODE_APPEND文件内容可追加
模式:MODE_PRIVAT文件内容被覆盖
3.读取:为有缓存的读取

 sbd.append(getFilesDir().getCanonicalPath());
 //输出规范路径

4.删除:deleteFile(“text.txt”);删除文件deleteFile()方法用于内存储
下面我们来看一下具体实现的代码
首先是InnerIoctivity.java
5.读取raw文件夹、读取assets目录的不同点,一般来将raw建在res下,assets和raw同级,所以raw会生成R文件,而assets不会。

public class InnerIoctivity extends AppCompatActivity {
    private EditText content;
    private TextView show;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inner_ioctivity);
        Button save= (Button) findViewById(R.id.save);
        Button read= (Button) findViewById(R.id.read);
        Button 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 v) {
                saveFile();
            }
        });
        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               show.setText(readFile());
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteFile();
            }
        });
    }
    //删除文件
    private  void deleteFile(){
        //返回fileList() 文件下的所有文件
        String[] files = fileList();
        for(String str:files){
            Log.d("====", str);
            if(str.equals("text.txt")){
                deleteFile("text.txt");
                break;
            }
        }

    }
    //读取文件
    public String readFile(){
        //带缓存的读
        BufferedReader reader=null;
        FileInputStream fis=null;
        StringBuffer sbd=new StringBuffer();
        try {
            fis=openFileInput("text.txt");
            reader=new BufferedReader(new InputStreamReader(fis));
            try {
                //输出规范路径
                sbd.append(getFilesDir().getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            String row = "";
            //readLine行读取
            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();
    }
    //save文件到内存储
    public void saveFile(){
        FileOutputStream fos=null;
        //1.名字 2.程序私有的 (覆盖)MODE_PRIVATE, MODE_APPEND(不覆盖)
        try {
            fos=openFileOutput("text.txt",MODE_APPEND);
            String str =content.getText().toString();
            try {
                /*
                * openFileOutput 返回一个输出字节流
                * 指向的路径为data/data/包名、files/
                * 参数1:文件名称(如果不存在则自动创建)
                * 参数2:模式:MODE_APPEND文件内容可追加
                *        模式:MODE_PRIVAT文件内容被覆盖
                * */
                fos.write(str.getBytes());
                Toast.makeText(InnerIoctivity.this, "保存成功", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if(fos!=null){
                try {
                    fos.close();
                    fos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

然后是它的布局文件activity_inner_ioctivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.edu.jereh.android10.InnerIoctivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入内容"
        android:id="@+id/content"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存"
        android:id="@+id/save"
        android:layout_below="@+id/content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="37dp"
        android:layout_marginStart="37dp" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除"
        android:id="@+id/delete"
        android:layout_below="@+id/content"
        android:layout_toRightOf="@+id/save"
        android:layout_toEndOf="@+id/save" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/read"
        android:text="读取"
        android:layout_marginRight="45dp"
        android:layout_marginEnd="45dp"
        android:layout_below="@+id/content"
        android:layout_alignRight="@+id/content"
        android:layout_alignEnd="@+id/content" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:layout_below="@+id/save"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

下面是效果图
这里写图片描述
为了方便理解,我让它输出了规范路径
下面是raw文件夹、读取assets目录的不同点
ReadRawAndAssetsActivity.java

public class ReadRawAndAssetsActivity extends AppCompatActivity {
    private Button raw,assets;
    private TextView show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_raw_and_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 v) {
                show.setText(readRaw());
            }
        });
        assets.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.setText(readAssets());

            }
        });
    }
    //读取assets目录
    public String readAssets(){
        StringBuilder sbd=new StringBuilder();
        BufferedReader reader=null;
//        InputStream is=null;
        try {
            InputStream is= getResources().getAssets().open("city");
            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();
    }
}

activity_read_raw_and_assets.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   tools:context="com.edu.jereh.android10.ReadRawAndAssetsActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/raw"
        android:text="读取raw"
        android:layout_below="@+id/show"
        android:layout_toRightOf="@+id/assets"
        android:layout_toEndOf="@+id/assets"
        android:layout_marginTop="35dp" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/assets"
        android:text="读取assets"
        android:layout_alignTop="@+id/raw"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:text="显示"
        />
</RelativeLayout>

SD卡的存储、读取、删除

实现步骤:加入读写SD卡权限
判断SD卡是否存在
读写文件
一定要写呀(必须有)和内存储的不同:

//获取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();

下面是读取、存储、删除的具体操作
SaveToSdCardActivity.java

public class SaveToSdCardActivity 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_ioctivity);
        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 v) {
                deleteF();
            }
        });
    }
    private  void deleteF(){
        //返回fileList() 文件下的所有文件
//        File file= Environment.getExternalStorageDirectory();
//            File fl=new File(file+"/sd.txt");
//        if(fl!=null){
//            fl.delete();
//        }
        String statu=Environment.getExternalStorageState();
        if (!statu.equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();
        }
        File file= Environment.getExternalStorageDirectory();
        File fl=new File(file ,"sd.txt");
        if(fl.exists()){
            fl.delete();
            Toast.makeText(this, "文件已删除", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
        }
    }
    //保存文件到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());
            //输出流的构造参数1:可以是File对象,也可以是文件路径
            //输出流的构造参数2:默认为fasle=>覆盖内容:true=>追加内容
//            File myFile=new File(file.getCanonicalPath()+"/sd.txt");
//            fos=new FileOutputStream(myFile);
            //加true追加模式
            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();
    }
}

activity_inner_ioctivity.xml和之前的用的是同一个布局,在这里就不再重复一遍了

读取网络图片、保存网络图片

运用Bitmap:
通过Bitmap(位图)压缩的方法(compress)保存图片到SD卡
参数一:图片格式(PNG,JPRG,WEBP)
参数二:图片质量(0-100)
参数三:输出流
运用Http传输,因为是耗时操作,所以需要异步任务类
以下为从网络读取图片,保存图片的代码
SDImgctivity.java

public class SDImgctivity extends AppCompatActivity {
    private ImageView img,showImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sdimgctivity);
        img=(ImageView)findViewById(R.id.img);
        showImg= (ImageView) findViewById(R.id.showImg);
    }
    //从SD卡读取图片
    public void readImg(View view){
        String path = Environment.getExternalStorageDirectory()+"/1.png";
        //方法一:根据URI 加载图片
        //showImg.setImageURI(Uri.parse(path));
        //方法二:通过BitmapFactory 的静态方法 decodeFile() 参数为图片路径
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        showImg.setImageBitmap(bitmap);
        //方法三:通过BitmapFactory 的静态方法 decodeStream 参数为输入流InputStream
//        try {
//            BitmapFactory.decodeStream(new FileInputStream(path));
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
    }
    public void HtSD(View view){
        String url = "http://pic3.nipic.com/20090622/2605630_113023052_2.jpg";
        new SaveHttpImg().execute(url);
    }
    public class SaveHttpImg extends AsyncTask<String,Void,String> {

        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection con = null;
            InputStream is = null;
            try {
                URL url = new URL(params[0]);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(5 * 1000);
                File root = Environment.getExternalStorageDirectory();
                FileOutputStream fos = new FileOutputStream(root + "/http.jpg");
                //http响应码200成功 404未找到 500发生错误
                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(SDImgctivity.this, "保存路径:" + s, Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(SDImgctivity.this,"保存失败:",Toast.LENGTH_SHORT).show();
            }
        }
    }
        public void HttpImg(View view) {
            String url = "http://pic3.nipic.com/20090622/2605630_113023052_2.jpg";
            new MyGetJob().execute(url);
        }

        public class MyGetJob extends AsyncTask<String, Void, Bitmap> {
            // onPostExecute在主线程中执行命令
            //doInBackground在子线程中执行命令
            //doInBackground执行之后会到onPostExecute中
            @Override
            protected Bitmap doInBackground(String... params) {
                HttpURLConnection con = null;//为了抛异常
                InputStream is = null;
                Bitmap bitmap = null;
                try {
                    URL url = new URL(params[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) {
                            Log.d("==j==", "509");
                            e.printStackTrace();
                        }
                    }
                    if (con != null) {
                        con.disconnect();
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                showImg.setImageBitmap(bitmap);

            }
        }

        public void saveImg(View view) {
            //读取ImageView中的图片
            BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable();
            Bitmap bitmap = bitmapDrawable.getBitmap();
            //获取根目录
            File root = Environment.getExternalStorageDirectory();
            //定义输出流
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(root + "/1.png");
             /*通过Bitmap(位图)压缩的方法(compress)保存图片到SD卡
        参数一:图片格式(PNG,JPRG,WEBP)
        参数二:图片质量(0-100)
        参数三:输出流
        */
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


}

布局文件activity_sdimgctivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.edu.jereh.android10.SDImgctivity">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:id="@+id/img"
        android:scaleType="center"
        android:src="@mipmap/b"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/save"
        android:layout_below="@id/img"
        android:onClick="saveImg"
        android:text="保存"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/read"
        android:onClick="readImg"
        android:text="读取图片"
        android:layout_below="@+id/save"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/HtImg"
        android:onClick="HttpImg"
        android:text="读取网络图片"
        android:layout_below="@+id/read"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/HtSDImg"
        android:onClick="HtSD"
        android:text="保存网络图片"
        android:layout_below="@+id/HtImg"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:id="@+id/showImg"
        android:scaleType="center"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

下面是效果图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值