需要帮助将文件写入外部存储

时间:2017-02-08 07:01:45

标签: java android file io

我一直在互联网上搜索几个小时,试图找到一个真正适合我的文件编写功能。到目前为止,我在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清单包含两种权限:

<?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)

非常感谢任何帮助,谢谢你。

1 个答案:

答案 0 :(得分:0)

我假设您未能获取文件路径,因为您在执行方法时没有询问运行时权限。在这里,您可以查看以下代码。

首先,检查您设备的操作系统版本是否高于棒棒糖。如果在上面,则显示权限弹出对话框。

final int MyVersion = Build.VERSION.SDK_INT;
if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1)
{
    if (!checkIfAlreadyhavePermission())
    {
        ActivityCompat.requestPermissions(ProfileActivity.this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
    }
    else
    {
        writeToFile(data, ctx);
    }
}
else
{
    writeToFile(data, ctx)
}

 private boolean checkIfAlreadyhavePermission() {
    int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
    return result == PackageManager.PERMISSION_GRANTED;
}

然后在OnRequestPerMissionResult()中定义“允许”和“拒绝”按钮功能。

 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    writeToFile( data, ctx);

                } else {
                    Toast.makeText(YourActivity.this, "Please provide permission", Toast.LENGTH_LONG).show();
                }
                break;
            }
    }

如果这样可以解决问题,请告诉我。