存取在SD卡中

来源:互联网 发布:以撒的结合 mac 下载 编辑:程序博客网 时间:2024/05/22 07:51
//读取文件操作test.txtpublic String readFile(String fileName) throws IOException {    String res = "";    try {//判断sd卡是否存在        if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {            String SDPATH = Environment.getExternalStorageDirectory().getPath() + "//";            File file = new File(SDPATH + "/" + fileName);            if (!file.exists()) {                file.createNewFile();                res = "亲,有事忙无法接电话,请稍后联系!";                writeFile(fileName, res);            } else {                //得到资源中的asset数据流                FileInputStream fis = new FileInputStream(file);                int length = fis.available();                byte[] buffer = new byte[length];                fis.read(buffer);                res = EncodingUtils.getString(buffer, "UTF-8");                fis.close();            }        } else            Toast.makeText(this, "sd卡不存在,读取失败", Toast.LENGTH_SHORT).show();    } catch (Exception e) {        e.printStackTrace();    }    return res;}//写文件public void writeFile(String fileName, String write_str) throws IOException {    if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {        String SDPATH = Environment.getExternalStorageDirectory().getPath() + "//";        File file = new File(SDPATH + "/" + fileName);        System.out.println("9999999999999999" + SDPATH + "/" + fileName);        FileOutputStream fos = new FileOutputStream(file);        byte[] bytes = write_str.getBytes();        fos.write(bytes);        fos.close();        Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();    } else        Toast.makeText(this, "sd卡不存在,写入失败", Toast.LENGTH_SHORT).show();}
原创粉丝点击