【问题标题】:Android 7.1.1 cannot create file or folders in external storage. FileNotFoundExceptionAndroid 7.1.1 无法在外部存储中创建文件或文件夹。 FileNotFoundException
【发布时间】:2017-09-05 19:57:33
【问题描述】:

我试图在文本文件中捕获传感器数据,当我通过 USB 将手机连接到 PC 时,我可以从手机的“外部存储”中提取这些数据,这样我就可以通过 python 脚本运行文本文件以进行绘图。我还没有实现传感器部分,因为我无法创建可以在创建后从手机复制到 PC 的文件。

我尝试创建一个文件夹,但它没有创建文件夹,我还尝试创建一个文件,它也失败了,然后它抛出一个文件不存在的异常。我不知所措,因为我已将权限添加到清单文件中,如下所示。有什么我想念的吗?我已经做了很多搜索,似乎没有任何解决方案可以解决我的问题,并且 developer.android.com 网站除了添加我已经添加到清单文件中的行之外没有解释任何有关权限的内容。

我没有 SD 卡,因此使用 sd 卡无法解决我的问题

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mike.project_final">

    <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:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>


        </activity>
    </application>

    </manifest>

这是我到目前为止所做的全部代码,它会引发错误。

    package com.example.mike.project_final;

    import android.content.Context;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Environment;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.hardware.Sensor;
    import android.view.View;
    import android.widget.TextView;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.PrintWriter;

    public class MainActivity extends AppCompatActivity implements SensorEventListener {



TextView xTV, yTV, zTV, writeTV;
SensorManager sManager;
Sensor sAccelerometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    xTV = (TextView) findViewById(R.id.xTV);
    yTV = (TextView) findViewById(R.id.yTV);
    zTV = (TextView) findViewById(R.id.zTV);
    writeTV = (TextView) findViewById(R.id.writeTV);
}

/* 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;
}

public void createFile(View view) {

    File root = android.os.Environment.getExternalStorageDirectory();
    File dir = new File (root.getAbsolutePath() + "/project_test");
    if (!dir.exists()){
        dir.mkdir();
        xTV.setText("Created");
    }
    else{
        xTV.setText("Exists");
    }
    File file = new File(dir, "myData.txt");

    try {
        FileOutputStream f = new FileOutputStream(file);
        PrintWriter pw = new PrintWriter(f);
        pw.println("Hi , How are you");
        pw.println("Hello");
        pw.flush();
        pw.close();
        f.close();
    } catch (Exception e) {
        writeTV.setText(e.toString());
    }
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy){
    //do nothing
}
@Override
public void onSensorChanged(SensorEvent event) {

}
}

如果需要,任何有关如何设置其余权限的帮助将不胜感激!

编辑 1: 权限问题已解决,谢谢。我现在有一个问题,我创建的文件夹不是作为文件夹创建,而是作为文件创建,如下图所示。我到底做错了什么? https://i.imgur.com/srKXJc1g.png 不幸的是,我没有足够的声誉来发布图片。

【问题讨论】:

  • 我设法让权限正常工作,但使用 mediascannerconnection 的整个过程让我无法接受。它会创建,当我尝试发现该文件夹时,它不会显示为文件夹,而是显示为 4kB 大小的空白白色文档?在这方面您可以提供什么建议?
  • 在调用 MediaScannerConnection 之前,请确保您已将文件完全写入磁盘。请参阅我的另一本不相关的书籍样本中的these lines
  • dir.mkdir();。你哭了 Created 但你应该检查返回值,因为 mkdirs() 可能会失败。如果是这样,您应该返回。

标签: java android xml file


【解决方案1】:

我的回答有点晚了,但希望它对某人有所帮助。 从 android 6 开始,您需要在应用程序运行时向用户请求权限,然后才能允许您的应用程序修改外部存储。 (因为它被归类为“危险权限”。阅读文档以了解更多信息https://developer.android.com/guide/topics/permissions/overview#permission-groups。)

那么你如何请求许可。?好吧,这种特定情况下的代码类似于下面的代码(阅读此处https://developer.android.com/training/permissions/requesting#java 以更好地理解);

 private final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 2;

 public checkWritePermissionAndCreateFile(){
 // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
            } else {
                // No explanation needed; request the permission
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            // Permission has already been granted
            // Carry out functionality that you needed permission for 
             createFile();                  
        }

@Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted
                createFile();
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission. 
            }
            return;
        }
        // other 'case' lines to check for other
        // permissions this app might request.
    }

}

}

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 2014-04-17
    • 2016-07-21
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多