Java 将图像保存到外部存储器(如果可用)

Java 将图像保存到外部存储器(如果可用),java,android,Java,Android,如果外部存储可用,我想将壁纸保存到外部存储,否则将其保存到设备内部存储。我的代码适用于安装了外部存储的设备,但在外部存储不可用时失败。我的短代码贴在下面 public FileOutputStream getOutStream(String fileName) throws FileNotFoundException{ if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOU

如果外部存储可用,我想将壁纸保存到外部存储,否则将其保存到设备内部存储。我的代码适用于安装了外部存储的设备,但在外部存储不可用时失败。我的短代码贴在下面

  public FileOutputStream getOutStream(String fileName) throws FileNotFoundException{
    if (Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        String sdpath = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES)
                + "/";
        mSavePath = sdpath + "DroidPack";
        File file = new File(mSavePath);
        if (!file.exists()) {
            file.mkdir();
        }
        File saveFile = new File(mSavePath, fileName);

        return new FileOutputStream(saveFile);


    }else{
        String sdpath = mContext.getFilesDir().getPath() + "/";
        mSavePath = sdpath + "DroidPack";
        File file = new File(mSavePath);
        if (!file.exists()) {
            file.mkdir();
        }
        return mContext.openFileOutput(fileName , Context.MODE_WORLD_READABLE); 
        }
}
}

看一下

不过,您应该尝试以下方法:

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}
你只是在检查一个条件

希望有帮助