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

时间:2017-07-28 11:05:57

标签: android io storage

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

中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()会创建所有缺少的目录。

4 个答案:

答案 0 :(得分:3)

您可以尝试使用以下内容:

    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();

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

希望这有帮助!

答案 1 :(得分:1)

试试这种方式

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

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

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

答案 2 :(得分:1)

  

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

作为用户,您无法访问Android SDK引用的应用程序部分internal storage,这就是您正在使用的

用户可以访问Android SDK external storage

答案 3 :(得分:1)

我不能发表评论,因为声誉太低,所以我需要这样回答。我会稍微修改 #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();
    }