3

誰かがこれを重複としてマークする前に、私はmkdirs()SO の方法について多くの質問をしましたが、どれもうまくいかなかったので、この問題には質問に値する特別なケースがあると信じています.

を使用してみmkdir()ましたが、ディレクトリのインスタンス化を次のように変更しFileました

new File(Environment.getExternalStorageDirectory())
new File(Environment.getExternalStorageDirectory().getAbsolutePath())
new File(Environment.getExternalStorageDirectory(), "Directory")
new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Directory")
new File(Environment.getExternalStorageDirectory().toString + "/Directory")

そして何も機能しません。

注:WRITE_EXTERNAL_STORAGEマニフェストにも許可があります。

ここに私のコードスニペットがあります:

File rootDirectory = new File(Environment.getExternalStorageDirectory(), getActivity().getPackageName());

File directory = new File(rootDirectory, "Directory");
if (!directory.exists()) {
    if(directory.mkdirs()){
       Log.d("log", "exists");
    } else {
       Log.d("log", "not exists");
    }
 }
4

2 に答える 2

2

mkdirs は完全なフォルダー ツリーを作成し、mkdir は完全なフォルダー ツリー パスの最後のフォルダーのみを作成します。

次のようなコードを使用します。

String foldername = "HelloWorld";
                 File dir = new File(Environment.getExternalStorageDirectory() + "/" + foldername);
                if (dir.exists() && dir.isDirectory()) {
                    Log.d("log", "exists");
                } else {
                    //noinspection ResultOfMethodCallIgnored
                    dir.mkdir();
                    Log.d("log", "created");
                }
于 2015-08-14T03:14:23.740 に答える
1

これを使って

File rootDirectory = new File(Environment.getExternalStorageDirectory(), 
      new File(Environment.DIRECTORY_DOCUMENTS, getActivity().getPackageName()));
   // if you target below api 19 use this => DIRECTORY_DOWNLOADS
  // now your old code follows life is good
File directory = new File(rootDirectory, "Directory");
if (!directory.exists()) {
    if(directory.mkdirs()){
       Log.d("log", "exists");
    } else {
       Log.d("log", "not exists");
    }
 }

詳細はこちらこちら

あなたのコメントから

しかし、フォルダーに保存しようとしているファイルをユーザーに見られたくない

内部メモリを使用して、これを呼び出すことができます[getDir(java.lang.String, int)]( http://developer.android.com/reference/android/content/Context.html#getDir(java.lang.String , int ) )))

それが役立つかどうか教えてください

于 2015-08-14T03:10:14.907 に答える