不使用mkdir()或mkdirs()创建目录

时间:2016-04-15 22:02:12

标签: java android

以下是我的MainActivity.java代码。根据toasts的错误是在创建目录。

MainActivity.java

@Override
protected void onActivityResult(int requestcode,int resultcode,Intent data){
    super.onActivityResult(requestcode,resultcode,data);
     if (requestcode == TAKE_PICTURE) 
        {
        if(resultcode== Activity.RESULT_OK){

            ImageView imageHolder = (ImageView)findViewById(R.id.image_camera);
            Bitmap bitmap = (Bitmap)data.getExtras().get("data");

            String partFilename = currentDateFormat();
            storeCameraPhotoInSDCard(bitmap, partFilename);

            // display the image from SD Card to ImageView Control
            String storeFilename = "photo_" + partFilename + ".jpg";
            Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
            imageHolder.setImageBitmap(mBitmap);
        }
        }
 }

  private String currentDateFormat(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
        String  currentTimeStamp = dateFormat.format(new Date(0));
        return currentTimeStamp;
    }
  /* Checks if external storage is available for read and write */
  public boolean isExternalStorageWritable() {
      String state = Environment.getExternalStorageState();
      if (Environment.MEDIA_MOUNTED.equals(state)) {
          Toast.makeText(MainActivity.this, "WriteMode ON", Toast.LENGTH_SHORT).show();
          return true;
      }
      Toast.makeText(MainActivity.this, "WriteMode OFF", Toast.LENGTH_SHORT).show();
      return false;
  }

  /* Checks if external storage is available to at least read */
  public boolean isExternalStorageReadable() {
      String state = Environment.getExternalStorageState();
      if (Environment.MEDIA_MOUNTED.equals(state) ||
          Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
          Toast.makeText(MainActivity.this, "Mounted or ReadMode", Toast.LENGTH_SHORT).show();
          return true;
      }
      Toast.makeText(MainActivity.this, "no-Mounted or no-ReadMode", Toast.LENGTH_SHORT).show();
      return false;
  }

    private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
        boolean isAvailable=isExternalStorageWritable();
        if(isAvailable){
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,90, bytes);
            String imgUri =  "photo_" + currentDate + ".jpg";
            File appDirectory = new File(Environment.getExternalStorageDirectory(),"CountDotsAppImages");
            boolean success = appDirectory.mkdirs();
            if (success) {
                Toast.makeText(MainActivity.this, "Directory Created", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(MainActivity.this, "Failed - Error", Toast.LENGTH_SHORT).show();
            }
            File destination = new File(Environment.getExternalStorageDirectory(),"CountDotsAppImages/"+imgUri);
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            }
        catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    }

    private Bitmap getImageFileFromSDCard(String filename){
     File storageDir = new File(Environment.getExternalStorageDirectory() + "/", "CountDotsAppImages");

        Bitmap bitmap = null;
        File imageFile = new File(storageDir.getPath()+File.separator + filename);
        try {
            FileInputStream fis = new FileInputStream(imageFile);
            Toast.makeText(MainActivity.this, imageFile.toString() , Toast.LENGTH_LONG).show();
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

的AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>权限已添加

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.countdots"
    android:versionCode="1"
    android:versionName="1.0" android:installLocation="auto">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="23" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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>

</manifest>

祝酒词输出:
   已安装或已读取模式    WriteMode ON    目录不存在,创建它
  失败错误 //创建目录mkdir

时出错

我尝试使用mkdir()和mkdirs()

3 个答案:

答案 0 :(得分:1)

想出来。
至于,我正在使用Android 6.0进行编译。它要求用户授予权限。 因此,如果用户授予或不授予应用程序权限,则应插入并检查以下代码。然后,如果用户授予读取和写入清单的权限,则会更新并且volia !!!

if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        1);
            } else {
                //do something
            }
        } else {
                //do something
        }

答案 1 :(得分:0)

此代码适用于我

library(stargazer)
startup <- function(x, out=NULL, ...){
  undo <- gsub("\\\\textasteriskcentered", "*", stargazer(x, ...))
  restar <- gsub("* * *", "${}^{***}$", undo, fixed = TRUE)
  restar <- gsub("* *", "${}^{**}$", restar, fixed = TRUE)
  restar <- gsub("* ", "${}^{*}$", restar, fixed = TRUE)
  if(!is.null(out)) cat(restar, file = out, sep="\n")
  restar
}

startup(res, out = "test.tex",
          type = "latex",
          title = "Zivot-Andrews Test Statistics", 
          colnames = TRUE, 
          notes = "Sig. Levels: ${}^{***} p < .01$, ${}^{**} p < .05$, ${}^{*} p < .1$")

答案 2 :(得分:0)

要添加目录,您可以使用此方法。

isAvailable=ExternalStorageChecker.isExternalStorageWritable();
        if(isAvailable){

            dir = new File(myContext.getExternalFilesDir(null), newAlbumDir.getText().toString().trim());
            if(!dir.mkdirs()){
                Log.e("++++++","Directoy Already Exist");
                Log.e("External Directory Path","++++"+dir.getAbsolutePath());

            }
            else{
                Log.e("++++","Directory Created");
                Toast.makeText(myContext,"File Created on External",Toast.LENGTH_SHORT).show();
                Log.e("Externa Directory Path","++++"+dir.getAbsolutePath());
              }
        }
        else{
            Toast.makeText(myContext,"File Created on Internal",Toast.LENGTH_SHORT).show();

            Log.e("Internal Directory Path","++++"+myContext.getFilesDir().getPath());
            dir=new File(myContext.getFilesDir(),newAlbumDir.getText().toString());

        }

创建目录(目录)后,您可以使用它来创建文件。