首先,在开始具体操作前,我们必须熟悉安卓File类的构造函数,见我的文章安卓File类
</uses-permission>
文件夹:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)//判断是否有读写权限
{
File root = new File(Environment</span>.getExternalStorageDirectory().getPath() + "/sign/");//构造函数参数为路径
if (!root.exists())
byte[] bytes = txt.getBytes();
stream.write(bytes);
其次,明确需求,根据文件还是文件夹选择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();
}
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