Java 中 创建文件操作

来源:互联网 发布:js原型链概念 编辑:程序博客网 时间:2024/05/22 12:08

Section1  创建文件

if (Environment.MEDIA_MOUNTED.equals(        Environment.getExternalStorageState())){    String  path = Environment.getExternalStorageDirectory().getAbsolutePath();    path=path+File.separator+"1ATesthahag"+File.separator+"tempImage.png";    Toast.makeText(this,path,Toast.LENGTH_LONG).show();    File file = new File(path);    if (!file.exists()){        try {            file.createNewFile();        } catch (IOException e) {            e.printStackTrace();        }    }}
查看SD卡后发现没有创建成功
Section2  先添加文件夹再创建文件
if (Environment.MEDIA_MOUNTED.equals(        Environment.getExternalStorageState())){    String  path = Environment.getExternalStorageDirectory().getAbsolutePath();    path=path+File.separator+"1ATesthahah"+File.separator+"tempImage.png";    Toast.makeText(this,path,Toast.LENGTH_LONG).show();    File file = new File(path);    if (!file.getParentFile().exists()) {        file.getParentFile().mkdirs();    }    if (!file.exists()){        try {            file.createNewFile();        } catch (IOException e) {            e.printStackTrace();        }    }}
这回创建成功了
总结,在java中,若要创建一个文件,则其所在文件夹必须先存在,
---------------------------------------------------------------------
标准的创建步骤:
if (!file.getParentFile().exists()) {    file.getParentFile().mkdirs();}if (!file.exists()){    try {        file.createNewFile();    } catch (IOException e) {        e.printStackTrace();    }}