有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java创建文件夹

我正在尝试创建一个文件夹调用"YouDown",此时我不关心文件夹位于何处,但此时我只想知道如何创建它。我发现我的第一个问题是mkdir()mkdirs()被忽略,因为不知道它是一个布尔值。我创建了success的布尔值,现在它不会被忽略。接下来,我创建了一个日志。从检测到创建到已存在的每个步骤的d。它注册它"Doesn't exist""Being Created",然后是"Created""Creation Failed"。它跳转到"Creation Failed"。我现在发现的一切都是重复我过去几天阅读的内容。我还研究了如何将其应用于特定路径,比如我希望在目录音乐文件夹中创建的变量字符串

//最后一次尝试

String Tag2 = "YouDown"

if (!dir.exists()) {
       Log.d(Tag2,"Doesnt Exist");
       boolean success = false;

       try{
           success = dir.mkdir();
           Log.d(Tag2,"Being Created");

       }
       catch(SecurityException se){
           //handle it
       }
       if(success) {
       Log.d(Tag2, "Created");
       } else{
           Log.d(Tag2, "Creation Failed");
    }
}

//其他尝试

String path = "/sdcard/Music/Youdown"

if(new File(path).exists()){

Log.d(Tag2, "Exists");

} else {

Log.d(Tag2, "Being Created");
Boolean succes = new File(path).mkdir();

if(success){

  Log.d(Tag2, "Created"

 } else {

  Log.d(Tag2, "Failed"
}

最新尝试

File dir = new File(Environment.getExternalStorageDirectory(), path2);
    Boolean A = dir.mkdirs();

    if(A){
        Log.d(Tag2,"Created");
    }
    if(!A){
        Log.d(Tag2,"Failed");
    }

共 (2) 个答案

  1. # 1 楼答案

    如果您仅为应用程序创建目录,那么如果您的应用程序被删除,文件夹也会被删除,您可以使用getFilesDir()

    File internalDir = getContext().getFilesDir();
    String path = "/Music/Youdown";       
    // to create it you can call, new File(internalDir, path).mkdir();
    

    或者,如果您想要外部存储,您可以使用如下Environment.getExternalStorage();

    String path = "/Music/Youdown";       
    File f = new File(Environment.getExternalStorageDirectory(), path );
     if (!f.exists()) {
         f.mkdirs();
     }
    
  2. # 2 楼答案

    虽然Android有一个分级文件系统,但你的应用程序只能在某些地方读写。首先,我建议使用android.content.Context的方法getDir()。正如文件所述:

    Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.

    如果要访问共享目录,需要调用其他方法,例如Context.getExternalFilesDir()