在外部SD卡上创建目录,该目录将写入文本文件

时间:2019-02-04 20:30:27

标签: android

我正在尝试在table { border-collapse: collapse; } td { border: 1px solid black; padding: 3px; text-align: center; } .header { background: #ccf; }上创建一个文件夹,其中将包含一个文本文件,我可以从PC上拔下手机并读取该文件。

我拼凑了一个external SDcard,我认为它可以正常工作,但是找不到应该创建的文件夹。

snippet

当我跨过File path = Environment.getExternalStorageDirectory(); File dir = new File(path.getAbsolutePath() + "/iptestdata/"); if (!dir.exists()) { dir.mkdirs(); } String fileName = new SimpleDateFormat("yyyyMMddHHmmss'.txt'").format(new Date()); final File file = new File(dir, fileName); 中的debugger时,我看到正在Android Studio中创建并存储的路径为dir,并且我看到{{1} }以我要求的格式显示,但在Windows中无法通过/storage/emulated/0/iptestdata找到该文件。我该如何解决?

1 个答案:

答案 0 :(得分:0)

如果您创建文件并将其存储到存储目录中,则您要调用mkdirs()

File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(sdcard.getAbsolutePath() + " /dir - name /");
dir.mkdir();
File file = new File(dir, "File-Name.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
String data = "This is the content of my file";
os.write(data.getBytes());
os.close();

请检查目录是否已创建或以下方法

  public static boolean canWriteOnExternalStorage() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        Log.v("Activity", "Yes, can write to external storage.");
        return true;
    }
    return false;
}

在您的AndroidManifest.xml

中添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>