安卓写文件及文件夹

来源:互联网 发布:淘宝如何设置最低折扣 编辑:程序博客网 时间:2024/05/29 15:59
首先,在开始具体操作前,我们必须熟悉安卓File类的构造函数,见我的文章安卓File类

其次,明确需求,根据文件还是文件夹选择File类的构造函数。读写权限:在AndroidManifest文件中加入读写权限:

<!-- 往sdcard中写入数据的权限 --> 

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

</uses-permission> 

<!-- 在sdcard中创建/删除文件的权限 -->

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

文件夹:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)//判断是否有读写权限
{
File root = new File(Environment</span>.getExternalStorageDirectory().getPath() + "/sign/");//构造函数参数为路径
if (!root.exists())

{root.mkdirs();}


文件:需要先创建文件夹

File file = new File(Environment.getExternalStorageDirectory().getPath()+"/sign/",filename);//注意构造函数的选择

 if (!file1.exists())//上面new失败的情况下
{
file1.createNewFile();
}

FileOutputStream stream = new FileOutputStream(file);
byte[] bytes = txt.getBytes();
stream.write(bytes);

stream.close();

或者:

File file1=new File(Environment.getExternalStorageDirectory().getPath()+“/sign/”+"filename");//构造函数与上面不同

 if (!file1.exists())//上面new失败的情况下
{
file1.createNewFile();
}

FileOutputStream stream1 = new FileOutputStream(file1);

byte[] bytes = txt.getBytes();
stream1.write(bytes);

stream1.close();

函数需要捕捉异常,加上try...catch或者throw exception
0 0
原创粉丝点击