美文网首页
Android 中的文件读写操作

Android 中的文件读写操作

作者: 大灰狼zz | 来源:发表于2018-12-18 16:31 被阅读0次

IO流(操作文件内容): 字节流

检查外部存储的状态

/**
     * 外部存储的状态
     *
     * @return
     */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        Log.e("state=", "" + state);
        return false;
    }

向外部存储写入字符串、图片

 private void writeStringToFile(String str) {
        if (!isExternalStorageWritable()) {
            return;
        }

        File dir = getExternalFilesDir("text");
        Log.e(TAG, "writeStringToFile: dir = " + dir.getAbsolutePath());

        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(dir, "str.txt");
        if (file.exists()) {
            file.delete();
        }

        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            file.createNewFile();

            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);

            bos.write(str.getBytes());

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

    private void writeImageToFile(Bitmap bitmap) {
        if (!isExternalStorageWritable()) {
            return;
        }

        File dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        Log.e(TAG, "writeImageToFile: dir = " + dir.getAbsolutePath());

        if (!dir.exists()) {
            dir.mkdirs();
        }

        File file = new File(dir, "ic.png");
        if (file.exists()) {
            file.delete();
        }

        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            file.createNewFile();

            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);

            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            bos.flush();

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

读取外部存储中的文本文件,图片文件

private String readStringFromFile() {
        if (!isExternalStorageWritable()) {
            return null;
        }

        File dir = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        Log.e(TAG, "readStringFromFile: dir = " + dir.getAbsolutePath());

        if (!dir.exists()) {
            return null;
        }

        File file = new File(dir, "str.txt");
        if (!file.exists()) {
            return null;
        }

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        StringBuffer sb = new StringBuffer();
        try {
            fis = new FileInputStream(file);//通过字节流获取
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);

            String line;
            sb.append(br.readLine());
            while ((line = br.readLine()) != null) {
                sb.append("\n" + line);
            }

            br.close();
            isr.close();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    private Bitmap readBitmapFromFile() {
        if (!isExternalStorageWritable()) {
            return null;
        }

        File dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        Log.e(TAG, "readBitmapFromFile: dir = " + dir.getAbsolutePath());

        if (!dir.exists()) {
            return null;
        }

        File file = new File(dir, "ic.png");
        if (!file.exists()) {
            return null;
        }

        FileInputStream fis = null;
        BufferedInputStream bis = null;

        Bitmap bitmap = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);

            bitmap = BitmapFactory.decodeStream(bis);

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

        return bitmap;
    }

从文件中读取数据

/**
     * 从文件中读取数据
     *
     * @param context
     * @return
     * @throws IOException
     */
    public static String readFile(Context context) throws IOException {

        StringBuilder sb = new StringBuilder("");

        File file = new File(context.getExternalFilesDir("voice") + "/voice.pcm");
        //打开文件输入流
        FileInputStream inputStream = new FileInputStream(file);

        byte[] buffer = new byte[1024];
        int len = inputStream.read(buffer);
        //读取文件内容
        while (len > 0) {
            sb.append(new String(buffer, 0, len));

            //继续将数据放到buffer中
            len = inputStream.read(buffer);
        }
        //关闭输入流
        inputStream.close();
        return sb.toString();
    }

如何读取 assets 文件夹中的文件

参考:
AssetManager
assets 文件夹用于存储应用需要的文件,在安装后可直接从其中读取使用或者写入本地存储中
Android Studio 默认不建立该文件夹,可以手动新建 : app -> src -> main -> assets
或者,右键 main -> New -> Folder -> Assets Folder
AssetManager 对象可以直接访问该文件夹:

获取方法:

AssetManager assetManager = this.getApplicationContext().getAssets();

使用函数 open 可以打开 assets 文件夹中对象,返回一个 InputStream 对象:
open

获取方法:

inputStream = assetManager.open("label.txt");
读取assets中文本文件
private String readStringFromAssets() {
        AssetManager assetManager = this.getApplicationContext().getAssets();
 
        InputStream inputStream = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
 
        StringBuffer sb = new StringBuffer();
        try {
            inputStream = assetManager.open("label.txt");
            isr = new InputStreamReader(inputStream);
            br = new BufferedReader(isr);
 
            sb.append(br.readLine());
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append("\n" + line);
            }
 
            br.close();
            isr.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
        return sb.toString();
    }
读取assets中文件,并写入本地
private boolean readDataFromAssets() {
    if (!isExternalStorageWritable()) {
        return false;
    }
 
    InputStream inputStream = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
 
    File dir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    Log.e(TAG, "readDataFromAssets: dir = " + dir.getAbsolutePath());
 
    if (!dir.exists()) {
        dir.mkdirs();
    }
 
    try {
        inputStream = getAssets().open("app-debug.apk");
 
        File file = new File(dir, "app-debug.apk");
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
 
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
 
        byte[] bytes = new byte[1024];
        while (inputStream.read(bytes) > 0) {
            bos.write(bytes, 0, bytes.length);
        }
 
        inputStream.close();
        bos.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    return true;
}

相关文章

  • 数据存储与访问之——文件存储读写

    1.Android文件的操作模式 在java中要想对文件做读写操作,只需创建 文件,读写数据即可,Android却...

  • android 读写文件

    title: android 读写文件 基本知识参照博客 Android - 文件读写操作 总结

  • Android 中的文件读写操作

    IO流(操作文件内容): 字节流 检查外部存储的状态 向外部存储写入字符串、图片 读取外部存储中的文本文件,图片文...

  • Android中文件读写操作

    Android开发中,离不开对文件的操作。本文首先介绍了使用java对文件进行基本的读写操作,而后介绍了A...

  • Android 中的文件操作

    Android 文件操作 概述 Android 中的文件操作主要涉及到两个部分,一个是内部存储的读写,一个是外部存...

  • Python 学习笔记6 2018-04-13

    文件操作: 1,文件的读写操作 2,文件的各种系统操作 3,存储对象 1,文件的读写操作 读写数据: ...

  • python文件相关操作

    一. 文件的读写操作基于字符read & write最基本的文件操作当然就是在文件中读写数据。打开一个文件的操作:...

  • Python之文件操作

    文件读写 文件读写是最基本的IO操作,在Python中内置了open函数来用于文件的读写操作,此函数创建一个文件对...

  • 2018-01-31

    java中对文件的读写操作

  • Python学习_IO文件操作

    在编程工作中,时常需要对各种文件进行操作。读写文件是最常见的IO编程,Python中内置了读写文件的函数。读写文件...

网友评论

      本文标题:Android 中的文件读写操作

      本文链接:https://www.haomeiwen.com/subject/roibiftx.html