如何将文件写入sd卡?(安卓系统)没有错误,但没有写入任何内容



我是开发android应用程序的新手。而且我的第一个项目已经挑战重重。我的应用程序应该能够通过单击"保存"按钮将EditText字段列表保存到文本文件中。但我没有成功地将文件写入我的SD卡。

我的代码:(按钮调用MainActivity.java中的功能)

public void saveData(View view){
        try{
        File sdcard = Environment.getExternalStorageDirectory();
        // to this path add a new directory path
        File dir = new File(sdcard.getAbsolutePath() + "/myapp/");
        // create this directory if not already created
        dir.mkdir();
        // create the file in which we will write the contents
        File file = new File(dir, "datei.txt");

        FileOutputStream os = new FileOutputStream(file);
        String data = "some string";
        os.write(data.getBytes());
        os.flush();
        os.close();
        }
        catch (IOException e){
            Log.e("com.sarbot.FitLogAlpha", "Cant find Data.");
        }
    }

有了谷歌,我找到了另一种方法:

public void saveData3(View view){
    FileWriter fWriter;
    File sdCardFile = new File(Environment.getExternalStorageDirectory() + "/datafile.txt");
    Log.d("TAG", sdCardFile.getPath()); //<-- check the log to make sure the path is correct.
    try{
         fWriter = new FileWriter(sdCardFile, true);
         fWriter.write("CONTENT CONTENT UND SO");
         fWriter.flush();
         fWriter.close();
     }catch(Exception e){
              e.printStackTrace();
     }
}

在我的manifest.xml中,我设置了权限:

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

开发者指南中的函数返回True->SD卡是可写的。

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

res/layout/activity_main.xml中有一些TextViewsEditText以及带有android:onClick="saveData"参数的保存按钮。函数被调用。SD卡是可写的。并且没有IO错误。但按下按钮后(没有错误),我的SD卡上仍然没有新文件。我已经尝试过手动创建文件,只是追加,但没有任何更改。我也尝试了BufferedWriter的其他功能。。但没有成功。

我正在运行我的索尼Xperia E与USB调试模式。在我的电脑上卸载并安装SD卡,但找不到文件。也许它只在手机上可见?它不存在?我不知道该怎么办,因为我没有任何错误。我需要计算机上这个文件的内容进行计算。

:编辑:问题不在代码中。。就在我抬头看的地方。外部存储->SD卡似乎是内部的,可移动SD卡是->ext_card。

此行之后,

 File file = new File(dir, "datei.txt");

添加此代码

 if ( !file.exists() )
 {
      file.createNewFile();         // This line will create new blank line.
 }
代码中缺少

os.flush()。在os.close() 之前添加此代码段

相关内容

最新更新