2017-07-30 73 views
0

我似乎无法弄清楚如何通过android应用程序创建目录/文件到内部存储器。我有以下代码:Android应用程序:如何在内部存储器中创建目录

public class Environment extends SurfaceView implements SurfaceHolder.Callback { 
    public static String FILE_PATH; 
    //other unimportant variables 

    public Environment(Conext context) { 
     super(context); 
     FILE_PATH = context.getFilesDir() + "/My Dir/"; 
     File customDir = new File(FILE_PATH); 
     if(!customDir.exists()) 
      System.out.println("created my dir: " + customDir.mkdir()); 

     File test = new File(FILE_PATH + "testFile.txt"); 
     try { 
      if(!test.exists()) 
       System.out.println("created test: " + test.createNewFile()); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
     //other unimportant stuff 
    } 
} 

然后我用ES文件浏览器,看看它创建的文件,我没有在任何地方看到的目录/文件,尽管它打印出“真正”的System.out的。 println()调用。

我在做什么错?

+0

检查:https://stackoverflow.com/a/40925801/6021469 –

回答

1

创建文件的路径位于应用程序私有位置。通常你不能从外面访问它。它实际上是在应用数据文件夹中创建的。不过看起来你想写在外部文件夹中。 要在外部存储写,你必须要求WRITE_EXTERNAL_STORAGE许可清单档案中的:

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

代码:

String folder_main = "My Dir"; 

    File f = new File(Environment.getExternalStorageDirectory(), folder_main); 
    if (!f.exists()) { 
     f.mkdirs(); 
    } 
    File test = new File(f , "testFile.txt"); 

在这里你会找到如何将创建在外部存储文件夹/文件。

Save a File on External Storage

+0

仍找不到目录,现在它说它无法创建目录:“创建我的目录:false”。尝试创建测试文件时,还会获得“java.io.IOException:Permission Denied” – Ryan

+0

请注意此答案的上半部分代码,其中将权限授予您的应用。 – ashubuntu

+0

@ashubuntu是的,我添加到清单,仍然不工作 – Ryan

0

您可以通过以下尝试:

ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext()); 
File directory = contextWrapper.getDir(getFilesDir().getName(), Context.MODE_PRIVATE); 
File file = new File(directory,”fileName”); 
String data = “TEST DATA”; 
FileOutputStream fos = new FileOutputStream(“fileName”, true); // save 
fos.write(data.getBytes()); 
fos.close(); 

这将写入文件在设备的内部存储(/data/user/0/com.yourapp/)

希望这有助于!

相关问题