【发布时间】:2017-02-08 07:01:44
【问题描述】:
我已经在互联网上搜索了几个小时,试图找到一个真正适合我的文件写入功能。到目前为止,我的 MainActivity.java 中有这个:
public void writeToFile(String data, Context ctx) {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File tempFile = new File(path, "houseDataFile.txt");
if(!tempFile.exists()){
tempFile.mkdirs();
}
try
{
FileOutputStream fOut = new FileOutputStream(tempFile);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(ctx, "Saved", Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
Log.w(TAG, "FileOutputStream exception: - " + e.toString());
}
}
我的 android manifest 包含这两个权限:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="my.package.application"xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
</activity>
<activity android:name=".Menu_activity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
虽然当我运行应用程序并调用 writeToFile() 时相当令人沮丧,但它给了我一个错误提示:
W/MainActivity: FileOutputStream exception: - java.io.FileNotFoundException: /storage/emulated/0/Documents/houseDataFile.txt: open failed: ENOENT (No such file or directory)
任何帮助将不胜感激,在此先感谢您。
【问题讨论】:
-
/storage/emulated/0/Documents存在吗? -
您设备的安卓版本是否 >= 6.x.x (Marsh Mallow) ?
-
been searching the internet for several hours now。如果您阅读过一些标记为 android 的 stackoverflow 页面,您会发现您的问题被多次报告。每周几次。