简体   繁体   English

将文件写入SD卡不起作用

[英]Writing a file to SD card not working

I wrote this to store a file in SD card, but it's not working. 我编写此文件是为了将文件存储在SD卡中,但无法正常工作。

public class TestarFilesActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        File root = Environment.getExternalStorageDirectory();

        try {
            if (root.canWrite()) {
                File file = new File(root, "agora.txt");
                FileWriter fwriter = new FileWriter(file);
                BufferedWriter out = new BufferedWriter(fwriter);
                out.write("Hello world");
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }TestarFilesActivity.this.finish();
    }
}

How is this problem caused and how can I solve it? 这个问题是怎么引起的,我该如何解决? I think it's everything right and I have write the permission in the manifest too. 我认为这没事,我也已在清单中写了许可。

检查报告此问题,似乎类似-检查sd卡是否可写将文本文件写入SD卡失败

if you run this application in android emulator you have to prepare sdcard through DevTools Terminal Emulator and check sdcard directory using linux command as $ls and allow to sdcard if not available prepare it and try the following 如果您在android模拟器中运行此应用程序,则必须通过DevTools Terminal Emulator准备sdcard,并使用linux命令$ ls检查sdcard目录,如果不可用则允许sdcard进行准备,然后尝试以下操作

File file = new File(root, "/sdcard/agora.txt");
FileWriter fwriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fwriter);
out.write("Hello world");
out.close();

//Use this in manifest.xml  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

您是否已在AndroidManifest.xml中对sdcard授予写权限?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM