Android 中的文件读写操作

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;
}

推荐阅读更多精彩内容