写入文件内部存储Android

时间:2015-08-07 20:23:12

标签: android save storage internal

鉴于此代码:

final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/";
    String file = dir + "info.txt";
    File newfile = new File(file);


        //Environment.getExternalStorageDirectory().toString()= /storage/emulated/0

String msgData="p1000";
        FileOutputStream outputStream;

        try {
            newfile.createNewFile();

            outputStream = openFileOutput(file, Context.MODE_PRIVATE);
            outputStream.write(msgData.getBytes());
            outputStream.close();
        } catch (Exception e) {
            e.toString();
            //e.printStackTrace();
        }

当我打开文件/storage/emulated/0/Documents/info.text时,我发现它是空的,而它应该有字符串" p1000&#34 ;;

为什么? 注意:我没有外部存储设备(外部SD卡)。

感谢。

2 个答案:

答案 0 :(得分:2)

你的Manifest中是否有WRITE_EXTERNAL_STORAGE权限?

试试这个:FileOutputStream outputStream = new FileOutputStream(file);

答案 1 :(得分:0)

如果您想使用内部存储,则不应该通过指向外部存储的路径(大致是SD卡)。在try-catch块中使用此行代替:

outputStream = openFileOutput("info.txt", Context.MODE_PRIVATE);

该文件将保存在Context.getFilesDir()返回的目录中。