zoukankan      html  css  js  c++  java
  • android 操作 sd 卡上的文件

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            try{
                write("cai.sq","welcome to the hell");
                String str = read("cai.sq");
                Log.v("sq", str);
            }catch(IOException e){e.printStackTrace();}
        }
        String read(String fileName)throws IOException
        {
            StringBuilder sb = new StringBuilder();
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))//判断sd卡是否已将插上,并且应用程序有读的权限
            {
                File sdCardDir = Environment.getExternalStorageDirectory();        //获取sd卡对应的存储目录
                FileInputStream fis = new FileInputStream(sdCardDir.getCanonicalFile() +"/" + fileName);// 获得指定文件对应的输入流
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));    //转化为缓冲流
                String line=null;
                while((line = br.readLine())!=null)
                {
                    sb.append(line);
                }
                br.close();
                fis.close();
                return sb.toString();
            }else
            return null;
        }
        
        void write(String fileName,String content) throws IOException
        {
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))//判断sd卡是否已将插上,并且应用程序有读的权限
            {
                File sdCardDir = Environment.getExternalStorageDirectory();        //获取sd卡对应的存储目录
                File targerFile = new File(sdCardDir.getCanonicalFile() +"/"+ fileName);    //获取目标文件
                RandomAccessFile raf = new RandomAccessFile(targerFile, "rw");        //“rw”表示可读可写
                raf.seek(targerFile.length());    //将文件指针移到文件末尾,为了追加数据
                raf.write(content.getBytes());    //写数据
                raf.close();
            }
        }
      //不要忘了在 manifest 中赋予权限
      //    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  <!-- 注册: 挂载、卸载文件系统的权限 -->
       
    // <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>   <!-- 注册: 向SD 卡写入数据的权限 -->
  • 相关阅读:
    solaris如何启动ssh服务
    网页实现插入图片—css与html的区别
    Python与RPC -- (转)
    Python中的异常处理 -- (转)
    Python的异常处理机制 -- (转)
    HTML 学习
    链表练习 链表反转 链表插入..
    php解决抢购秒杀抽奖等大流量并发入库导致的库存负数的问题
    PHP队列的实现 算法
    利用redis List队列简单实现秒杀 PHP代码实现
  • 原文地址:https://www.cnblogs.com/laoquans/p/3066399.html
Copyright © 2011-2022 走看看