繁体   English   中英

如何将文件写入SD卡? (Android)没有错误,但没有任何内容

[英]How to write file to sd-card? (Android) No errors, but nothing written

我是开发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.");
        }
    }

通过Google,我找到了另一种方法:

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其他功能..但是没有成功。

我正在使用USB调试模式运行Sony XperiaE。 将SD卡卸载并安装到我的PC上,但找不到该文件。 也许只在手机上可见? 它不存在吗? 我不知道该怎么办,因为我没有错误。 我需要计算机上此文件的内容进行计算。

:EDIT:问题不在代码中..只是在我查找的地方。 externalStorage-> sdCard似乎是内部的,而可移动sdcard是-> ext_card。

您的代码中缺少os.flush() os.close()之前添加此代码段

在这行之后

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

添加此代码

 if ( !file.exists() )
 {
      file.createNewFile();         // This line will create new blank line.
 }

暂无
暂无

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

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