【问题标题】:Save a file on Android documents?在 Android 文档上保存文件?
【发布时间】:2013-12-26 16:00:02
【问题描述】:

我直接在 Android 上创建一个 excel 文件。代码运行良好,我可以验证 .xls 是否已创建,并且可以从有根手机中检查它的内容。 但是,我想将 excel 文件保存在与项目本身不同的文件夹中(即 /data/data/mypackage/files/)。我想将它保存在普通的电话文档中,例如“/storage/sdcard0/Documents/test.xls”。尝试将 .xls 文件保存到该文件夹​​时,我收到一条消息“权限被拒绝”。

如何访问这些文件夹?

我在这里创建excel文件

WriteExcel test = new WriteExcel();
            test.setOutputFile("/data/data/com.example.interfaz/files/test.xls"); // here is where I want to save the file to "/storage/sdcard0/Documents/test.xls"
            try {
                test.write();

            } catch (WriteException e) {
                e.printStackTrace();
            } catch (IOException e) {
                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
            }

【问题讨论】:

    标签: android excel


    【解决方案1】:

    您是否为清单添加了权限?

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

    您也不应该对 SDCard 位置进行硬编码,因为它可以而且确实会在设备之间发生变化。

    改为使用Environment.getExternalStorageDirectory()

    【讨论】:

    • 在我的回答中忘记了这一点,但是阿门 Environment.getExternalStorageDirectory() 绝对是要走的路。
    【解决方案2】:

    查看此页面了解有关保存文件的更多信息:

    http://developer.android.com/training/basics/data-storage/files.html#GetWritePermission

    确保您在清单中具有将文件写入外部存储的权限:

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

    【讨论】:

    • 我太笨了。我以为我已经添加了权限,但它是 READ_EXTERNAL_STORAGE 而不是 WRITE。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多