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 卡写入数据的权限 -->
  • 相关阅读:
    stress工具使用指南和结果分析
    copy.c实现
    sysbench测试阿里云CPU
    sysbench测试阿里云ECS云磁盘的IOPS,吞吐量
    iostat详解
    sysbench_fileio.sh
    rm -f /var/lib/rpm/__db*;rpm --rebuilddb
    HeadFirst 13 (包装器, 过滤器) not Finish
    基于Linux的oracle数据库管理 part5( linux启动关闭 自动启动关闭 oracle )
    基于Linux的oracle数据库管理 part4( shell管理 上 )
  • 原文地址:https://www.cnblogs.com/laoquans/p/3066399.html
Copyright © 2011-2022 走看看