android - 在android中将文件写入sdcard

标签 android file android-sdcard

我想在 SD 卡上创建一个文件。在这里我可以创建文件并将其读/写到应用程序,但我在这里想要的是,文件应该保存在 sdcard 的特定文件夹中。我如何使用 FileOutputStream 做到这一点?

// create file
    public void createfile(String name) 
    {
        try
        {
            new FileOutputStream(filename, true).close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // write to file

    public void appendToFile(String dataAppend, String nameOfFile) throws IOException 
    {
        fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
        fosAppend.write(dataAppend.getBytes());
        fosAppend.write(System.getProperty("line.separator").getBytes());
        fosAppend.flush();
        fosAppend.close();
    }

最佳答案

这是我的代码中的一个示例:

try {
    String filename = "abc.txt";
    File myFile = new File(Environment
            .getExternalStorageDirectory(), filename);
    if (!myFile.exists())
        myFile.createNewFile();
    FileOutputStream fos;
    byte[] data = string.getBytes();
    try {
        fos = new FileOutputStream(myFile);
        fos.write(data);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

别忘了:

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

关于android - 在android中将文件写入sdcard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20369782/

相关文章:

android - 如何在 webview 中单击 URL 时获取文件名

android - 安装 Windows 10 周年更新后无法启动 Android 模拟器

php - 跨浏览器跨操作系统文件对话框(能够只选择目录和文件)非 Java

android - 保存并读取图像,但是打开文件夹时找不到

Android源码从sdcard读取文件出错

android - 谷歌播放 : The form field "Compliance Status" to delete a previously declared Permission for a new APK is not shown

android - 在Dart中从云中解析嵌套的JSON但出现类型错误

java - 以编程方式删除所有 SdCard 文件

c - 用C写入文件

android - 频繁写入 SD 卡的影响