使用FileInputStream和FileOutputStream读写sdcard卡下的文件

来源:互联网 发布:for在c语言中的作用 编辑:程序博客网 时间:2024/05/01 07:39
//需要在AndroidManifest中申请权限    //android.permission.MOUNT_UNMOUNT_FILESYSTEMS 创建删除文件    //android.permission.WRITE_EXTERNAL_STORAGE 写sd卡    final String FILE_NAME = "testSd.txt";    /**     * 读文件     * @return     */    private String read(){        StringBuffer stringBuffer = new StringBuffer();        //有sd卡        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){            try {                //创建输入流                String sdCardDir = Environment.getExternalStorageDirectory().getCanonicalPath(); //sd卡路径                File file = new File(sdCardDir  +  "//" +FILE_NAME);                FileInputStream fileInputStream = new FileInputStream(file);                int hasRead = 0; //读到的数据长度                byte [] buffer = new byte[1024];                //读数据                while((hasRead = fileInputStream.read(buffer)) > 0){                    stringBuffer.append(new String(buffer,0,hasRead));                }                fileInputStream.close();            }catch (IOException io){                io.printStackTrace();            }        }        return stringBuffer.toString();    }    /**     * 写文件     * @param strWrite     */    private void write(String strWrite){        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){            try {                //创建输出流                String sdCardDir = Environment.getExternalStorageDirectory().getCanonicalPath();                File file = new File(sdCardDir + "//" + FILE_NAME);                FileOutputStream fileOutputStream = new FileOutputStream(file);                fileOutputStream.write(strWrite.getBytes());                fileOutputStream.close();            }catch (IOException ioEx){                ioEx.printStackTrace();            }        }    }

0 0
原创粉丝点击