Android手机数据读写方法(内部存储、SD卡,网络加载,包内文件读取)

    本次实例以文本和图片为例,展示了Android手机内部存储的读写方法、SD卡的读写方法,包内文件的读取,以及网络文本及图片的加载与下载。

    项目文件在此:文档下载传送门

从网络加载图片或保存到本地。通过字符流进行读写。

Activity文件:

public class HttpImageActivity extends AppCompatActivity {

    private ImageView show;
    private Button download,save;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_image);
        show = (ImageView) findViewById(R.id.show);
        download = (Button) findViewById(R.id.download);
        save = (Button) findViewById(R.id.download2);
        download.setOnClickListener(new View.OnClickListener() {
            String[] strings= {"http://ww2.sinaimg.cn/thumb300/8ecc236cgw1evrrnv99jqj20qh0zkh7u.jpg"};
            @Override
            public void onClick(View view) {
                new showImg().execute(strings);
            }
        });

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                savePicture();
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            String[] strings= {"http://img.doooor.com/img/forum/201412/05/220220e93j9j809wcwz9hb.jpg"};
            @Override
            public void onClick(View view) {
                new downLoadImg().execute(strings);
            }
        });
    }

    public class showImg extends AsyncTask<String,Void,Bitmap> {

        //onPreExecute在主线程中执行命令,它会在doInBackground前执行。
        //通常会在这里做进度条的初始化,例如:下载进度
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
//        int a = 5;
        //必须实现的方法,可以理解成,在子线程中执行命令
        @Override
        //这里的...代表数组
        protected Bitmap doInBackground(String... strings) {
            HttpURLConnection httpURLConnection = null;
            InputStream is = null;
            Bitmap bitmap = null;
            try {
                URL url = new URL(strings[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(5*1000);
                httpURLConnection.setReadTimeout(5*1000);
                 /*
                    http 响应码
                    200:成功
                    404:未找到
                    500:发生错误
                     */
                if(httpURLConnection.getResponseCode()==200){
                    is=httpURLConnection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
//                    a=100;
                    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(httpURLConnection!=null){
                    httpURLConnection.disconnect();
                }
            }
            return null;
        }

        //在UI线程(主线程)中执行命令
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            show.setImageBitmap(bitmap);
//            Toast.makeText(getBaseContext(),""+this.a,Toast.LENGTH_SHORT).show();
        }
    }

    public class downLoadImg extends AsyncTask<String,Void,Bitmap> {

        //onPreExecute在主线程中执行命令,它会在doInBackground前执行。
        //通常会在这里做进度条的初始化,例如:下载进度
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        //        int a = 5;
        //必须实现的方法,可以理解成,在子线程中执行命令
        @Override
        //这里的...代表数组
        protected Bitmap doInBackground(String... strings) {
            HttpURLConnection httpURLConnection = null;
            InputStream is = null;
            Bitmap bitmap = null;
            try {
                URL url = new URL(strings[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(5*1000);
                httpURLConnection.setReadTimeout(5*1000);
                 /*
                    http 响应码
                    200:成功
                    404:未找到
                    500:发生错误
                     */
                if(httpURLConnection.getResponseCode()==200){
                    is=httpURLConnection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
//                    a=100;
                    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(httpURLConnection!=null){
                    httpURLConnection.disconnect();
                }
            }
            return null;
        }

        //在UI线程(主线程)中执行命令
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            FileOutputStream fos = null;
            String state = Environment.getExternalStorageState();
            //判断SD卡是否就绪
            if (!state.equals(Environment.MEDIA_MOUNTED)){
                Toast.makeText(getBaseContext(),"SD卡未就绪",Toast.LENGTH_SHORT).show();
                return;
            }
            File file = Environment.getExternalStorageDirectory();
            File myfile = null;
            try {
                myfile = new File(file.getCanonicalPath()+"/图片js.png");
                fos = new FileOutputStream(myfile);
                bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
                Toast.makeText(getBaseContext(),"下载完成",Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    //将程序中的图片保存到SD卡上
    public void savePicture(){
        FileOutputStream fos = null;
        BitmapDrawable bitmapDrawable = (BitmapDrawable) show.getDrawable();
        Bitmap bitmap = bitmapDrawable.getBitmap();
        String state = Environment.getExternalStorageState();
        //判断SD卡是否就绪
        if (!state.equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();
            return;
        }
        File file = Environment.getExternalStorageDirectory();
        File myfile = null;
        try {
            myfile = new File(file.getCanonicalPath()+"/子望.png");
            fos = new FileOutputStream(myfile);
            bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    //老师写的从网上下载图片
    public class SaveHttpImg extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {
            HttpURLConnection httpURLConnection = null;
            InputStream is = null;
            Bitmap bitmap = null;
            try {
                URL url = new URL(strings[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(5 * 1000);
                httpURLConnection.setReadTimeout(5 * 1000);
                File root = Environment.getExternalStorageDirectory();
                FileOutputStream fos = new FileOutputStream(root + "/http.jpg");
                if (httpURLConnection.getResponseCode() == 200) {
                    is = httpURLConnection.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 (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
            return null;

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(!s.equals("")){
                Toast.makeText(HttpImageActivity.this,"保存路径:"+s,Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(HttpImageActivity.this,"保存失败:"+s,Toast.LENGTH_SHORT).show();
            }
        }
    }
}


Layout文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="jerehdu.com.sharedpreferences.HttpImageActivity"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:id="@+id/show"
        android:scaleType="centerCrop"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/download"
        android:text="加载图片"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/download2"
        android:text="下载图片"/>
</LinearLayout>


预览图:

读取rawassets中的文件,将已有的图片保存到SD卡里,将SD卡的图片加载到应用里。

Activity文件:

public class ReadRawAndAssetsActivity extends AppCompatActivity {

    private Button raw,assets,save,read;
    private TextView show;
    private ImageView img,showImg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_raw_and_assets);
        raw = (Button) findViewById(R.id.bt1);
        assets = (Button) findViewById(R.id.bt2);
        save = (Button) findViewById(R.id.bt3);
        read = (Button) findViewById(R.id.bt4);
        show = (TextView) findViewById(R.id.tv1);
        img = (ImageView) findViewById(R.id.iv1);
        showImg = (ImageView) findViewById(R.id.iv2);
        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());
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                savePicture();
            }
        });

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                readPicture();
            }
        });
    }

    //读取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);
                sbd.append("\n");
            }
            Toast.makeText(this,"读取成功",Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sbd.toString();
    }

    //读取Assets文件夹
    public String readAssets(){
        StringBuilder sbd = new StringBuilder();
        BufferedReader reader = null;
        InputStream is = null;
        String row = "";
        try {
            is = getResources().getAssets().open("cityinfo");
            reader = new BufferedReader(new InputStreamReader(is));
            while ((row = reader.readLine())!=null){
                sbd.append(row);
                sbd.append("\n");
            }
            Toast.makeText(this,"读取成功",Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sbd.toString();
    }

    //将程序中的图片保存到SD卡上
    public void savePicture(){
        FileOutputStream fos = null;
        BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable();
        Bitmap bitmap = bitmapDrawable.getBitmap();
        String state = Environment.getExternalStorageState();
        //判断SD卡是否就绪
        if (!state.equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();
            return;
        }
        File file = Environment.getExternalStorageDirectory();
        File myfile = null;
        try {
            myfile = new File(file.getCanonicalPath()+"/机器人.png");
            fos = new FileOutputStream(myfile);
            bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
            Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    //将图片从SD卡上读取出来显示到ImageView上
    public void readPicture(){
        String path = Environment.getExternalStorageDirectory()+"/mei01.jpg";
        //方法一:根据URI 加载图片
//        showImg.setImageURI(Uri.parse(path));
        //方法二:通过BitmapFactory的静态方法 decodeFile(),参数为图片路径。
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        showImg.setImageBitmap(bitmap);
        //方法三:通过BitmapFactory的静态方法 decodeStream(),
        //参数为 输入流 InputStream;
//        BitmapFactory.decodeStream();
    }
}


Layout文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="jerehdu.com.sharedpreferences.ReadRawAndAssetsActivity"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:id="@+id/tv1"/>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:gravity="center">
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="读取Raw"
                    android:id="@+id/bt1"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="读取Assets"
                    android:id="@+id/bt2"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="保存图片"
                    android:id="@+id/bt3"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="读取图片"
                    android:id="@+id/bt4"/>
            </LinearLayout>
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="centerCrop"
                android:id="@+id/iv1"
                android:src="@mipmap/ic_launcher"/>
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="centerCrop"
                android:id="@+id/iv2"
                android:src="@mipmap/ic_launcher"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>


预览图:


EditView中输入文字,然后将其通过 FileOutputStream 保存到手机SD卡根目录,并且有读取该文件和删除该文件。

Activity文件:

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_save_to_sd_card);

        save = (Button) findViewById(R.id.save);
        read = (Button) findViewById(R.id.read);
        delete = (Button) findViewById(R.id.del);
        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();
            }
        });
    }

    //保存文件到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:默认为false=>覆盖内容;true=>追加内容
            File myfile = new File(file.getCanonicalPath()+"/SD.txt");
            fos = new FileOutputStream(myfile,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.flush();
                    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 = "";
            while ((row = reader.readLine())!=null){
                sbd.append(row);
            }
        } catch (FileNotFoundException e) {
            Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sbd.toString();
    }

    //从SD卡中删除文件
    public void removeFile(){

        String[] files = fileList();
        File myfile = null;
        String statu = Environment.getExternalStorageState();
        if(!statu.equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(this,"SD卡未就绪",Toast.LENGTH_SHORT).show();
        }
        File root = Environment.getExternalStorageDirectory();
        try {
            myfile = new File(root.getCanonicalPath()+"/SD.txt");
            myfile.delete();
        } catch (IOException e) {
            Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
        }
    }
}


Layout文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="jerehdu.com.sharedpreferences.SaveToSdCardActivity"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入内容"
        android:id="@+id/content"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/save"
            android:text="保存"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/read"
            android:text="读取"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/del"
            android:text="删除"/>
    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/show"/>
</LinearLayout>


预览图:




  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值