您的位置:首页 > 编程语言 > Java开发

Java 中 创建文件操作

2017-10-20 19:12 99 查看
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();}}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java