android - 将文件保存到内部存储

cmp*_*x96 1 io storage android

我知道这是一个双重帖子,但其他线程没有回答我的问题。我想在内部存储的Android目录中将文件写入我的应用程序目录

我在清单中添加了权限:

Manifest.xml代码:

 <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)

Java代码:

 File myPath = new File(getFilesDir(), "test.dat");            
    myPath.mkdirs();
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myPath);
        fos.write(bytes);
    } catch (Exception e) {

    }
Run Code Online (Sandbox Code Playgroud)

但是我的应用程序的目录没有创建,我无法通过搜索找到文件名。

编辑: 实际上抛出了 FileNotFoundException ,我的错。但我认为 mkdirs() 会创建所有丢失的目录。

小智 7

您可以尝试使用以下方法:

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();
Run Code Online (Sandbox Code Playgroud)

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