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

android - save file to internal storage

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

我在清单中添加了权限:

Manifest.xml代码:

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

Java代码:

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

    }

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

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

试试这个方法

 String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/filename";

            File dir = new File(path);
            if (!dir.exists())
                dir.mkdirs();

           // File file = new File(dir, "filename");

however the directory for my app is not created and I cannot find the filename via search.

作为用户,您无权访问 Android SDK 所指的 internal storage 您的应用程序部分,这正是您正在使用的部分。

用户可以访问 Android SDK 所称的 external storage

您可以尝试以下方法:

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/

由于信誉度太低,我不能发表评论,所以我需要这样回答。我会稍微修改#AndroidDevUser 答案,更改:

FileOutputStream fos = new FileOutputStream(“fileName”, true);

fos = new FileOutputStream(file, true);

此外,我会添加 try / catch 块。

    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 = null; // save
    try {
        fos = new FileOutputStream(file, true);
        fos.write(data.getBytes());
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }