android系统外部存储文件写操作的具体实现

来源:互联网 发布:阿sa长相 知乎 编辑:程序博客网 时间:2024/05/16 07:25

1

首先要申请权限

权限的申请

AndroidManifest 里面在application前

添加

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2

找到外部存储卡的路径


File sdDir = null; 
        boolean sdCardExist = Environment.getExternalStorageState()   
        .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
       if(sdCardExist)   
        {                               
          sdDir = Environment.getExternalStorageDirectory();//获取跟目录
          filePath=sdDir.toString();           
        }   

注意:3。4都要鞋子try语句里面才对

3

在外部存储卡上写自己的文件夹

File file1 = new File(wdir);
if (!file1.exists()) {
file1.mkdirs();
}


4

文件夹产生只有,就好做自己的文件了

 if (!file.exists()) {
   file.createNewFile();

}


下面是我实现的,把asset文件里面的txt文件复制到

外部存储卡的程序文件

  File sdDir = null; 
        boolean sdCardExist = Environment.getExternalStorageState()   
        .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
       if(sdCardExist)   
        {                               
          sdDir = Environment.getExternalStorageDirectory();//获取跟目录
          filePath=sdDir.toString();           
        }   
       
       String dir=filePath+"/"+"test/"+fileName;
       String wdir=filePath+"/"+"test/";
 file=new File(dir);
 Toast.makeText(getApplicationContext(),dir,
      Toast.LENGTH_SHORT).show();

try{

File file1 = new File(wdir);
if (!file1.exists()) {
file1.mkdirs();
}

   if (!file.exists()) {
   file.createNewFile();
Toast.makeText(getApplicationContext(),filePath+"创建",
        Toast.LENGTH_SHORT).show();

try {
InputStream in = getResources().getAssets().open("laobeijing.txt");
//获取文件的字节数
int lenght = in.available();
//创建byte数组
byte[]  buffer = new byte[lenght];
//将文件中的数据读到byte数组中
in.read(buffer);
result=new  String (buffer); 
} catch (Exception e) {
e.printStackTrace();
}
RandomAccessFile raf = new RandomAccessFile(file, "rw");
           raf.seek(file.length());
           raf.write(result.getBytes());
           raf.close();
           }
}catch (Exception e) {
e.printStackTrace();
}




0 0
原创粉丝点击