为什么创建新文件会引发异常?

时间:2014-11-25 20:48:13

标签: android android-camera android-file

我想用相机拍照,我想以特定格式保存(date.jpg)

这是我的代码:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
     File photoFile = null;
     try {
         photoFile = createFile();
         photoPath = photoFile.getAbsolutePath();
     } catch (IOException ex) {
         Log.i(SelfieConstantUtility.TAG, "IOException with creating file");
     }
     if (photoFile != null) {
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
        startActivityForResult(takePictureIntent,SelfieConstantUtility.REQUEST_TAKE_PHOTO);
     }
}

private File createFile() throws IOException{
    String timeStamp = new SimpleDateFormat(SelfieConstantUtility.DATEFORMAT).format(Calendar.getInstance().getTime());

    File image = new File(timeStamp+".jpg");
    image.createNewFile();
    return image;
}

这是我的Android清单:

<?xml version="1.0" encoding="utf-8"?>

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".DailySelfieActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

为什么不创建文件? 我认为问题出在这里,但我不知道:

image.createNewFile();

1 个答案:

答案 0 :(得分:3)

您正在使用构造函数

new File(String path)

timestamp +“。jpg”不是我想的路径......看看这个:

new File(Environment.getExternalStorageDirectory()
                      .getAbsolutePath(), timestamp+".jpg");