Android–SDcard文件读取和保存

时间:2014-05-19 22:36:15   收藏:0   阅读:456

背景                                                                                           

一些东西可以存在自己定义的文件里面,这个文件可以在手机中,可以在SD卡中,在这里就主要介绍一下在SD卡中的存储和读取吧~

代码                                                                                            

bubuko.com,布布扣
public class save {
    public static void savefile2card(Context context,String username,String password)
    {
        File file = null;
        FileOutputStream fos = null;
        try 
        {
            if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
            {
//    file = new File("/sdcard/info.txt");
                file = new File(Environment.getExternalStorageDirectory(),"info.txt");
                fos = new FileOutputStream(file);
                fos.write((username+"!!!!"+password).getBytes());    
            }
            else
            {
                Toast.makeText(context, "SD木有", Toast.LENGTH_LONG).show();
            }
        } 
        catch (Exception e) 
        {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            Toast.makeText(context, "Wrong", Toast.LENGTH_LONG).show();
            try 
            {
                fos.close();
            } 
            catch (IOException e1) 
            {
                // TODO 自动生成的 catch 块
                e1.printStackTrace();
            }
        }
    }
}
bubuko.com,布布扣

上面是存的代码,这里面用到了Environment.MEDIA_MOUNTED,查看是否挂载。

bubuko.com,布布扣
public class read {
    public static Map<String,String> getSaveFile(Context context)
    {
        //File file =new File(context.getFilesDir(),"info.txt");
        File file = new File(Environment.getExternalStorageDirectory(),"info.txt");
        
        try 
        {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String str = br.readLine();
            String[] infos = str.split("!!!!");
            Map<String,String> map = new HashMap<String, String>();
            map.put("username",infos[0]);
            map.put("password", infos[1]);
            br.close();
            return map;
        } 
        catch (Exception e)
        {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            return null;
        }
        finally
        {
            
        }
        
    }
}
bubuko.com,布布扣

上面是读取的代码,会存就会读了,存得进去那么就读得出来撒~

我是天王盖地虎的分割线                                                                

源代码:http://pan.baidu.com/s/1dD1Qx01

SDcard.zip

 

 

 

转载请注明出处:http://www.cnblogs.com/yydcdut/p/3720648.html

Android–SDcard文件读取和保存,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!