有没有一种方法可以在Android上的“我的文件”(外部存储)中创建文件夹并将文件写入此文件夹?

时间:2019-01-13 02:31:16

标签: java android android-studio io storage

我正在编写一个Android应用程序(使用Java),该应用程序使用OCR将手写内容转换为数字文本。我试图在代码中使用OCR函数生成的String并将其写入文本文件(OCR部分当前正在工作)。然后,我想创建一个文件夹(在手机的外部存储中,例如Samsung上的“我的文件”),然后将文本文件添加到该文件夹​​中,该文件夹仅包含用户创建的文件(用户应该可以访问和共享) )。

我已经进行了一些有关写手机外部存储的研究(包括其他StackOverflow问题),但是没有一个教程对我有用。

/* 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 File writeFolder ()

{

    File file = null;

    if (isExternalStorageWritable())

    {
        // Get the directory for the user's public directory.
       file = new File(Environment.getExternalStorageDirectory() + File.separator + "OCR Documents");

    }

    if (!file.mkdirs())
        Log.e(LOG_TAG, "Directory not created");

    else
        System.out.println(file.getAbsolutePath());

    return file;

}

上面的代码是我所拥有的,但是在测试之后,AbsolutePath为null。它似乎没有在电话的外部存储上创建文件夹。我将如何处理以便创建文件夹并可以将文件添加到该文件夹​​?

3 个答案:

答案 0 :(得分:0)

您创建目录的代码很好。

但是由于新版本的Android需要征得用户同意才能将文件写入外部存储,因此您可能会失去权限。

首先,请确保您在Manifest.xml中具有此权限:

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>

然后,由于WRITE_EXTERNAL_STORAGE被列为危险许可,如https://developer.android.com/guide/topics/permissions/overview#normal-dangerous所示,因此,您还需要显式请求用户许可。

最后,请求许可:

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

    // Permission is not granted
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // 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.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
} else {
    // Permission has already been granted
}

您还需要处理请求的响应:

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.
            } 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.
    }
}

上面的代码是从https://developer.android.com/training/permissions/requesting

复制而来的

您应该更彻底地阅读该链接,因为它可以很好地说明您需要向用户解释的内容,因为当Apps要求修改存储中文件的权限时,用户通常会非常警惕。

答案 1 :(得分:0)

您可以尝试一下,

  private void getWirtePermissionAndCreateDir() {
    if (Build.VERSION.SDK_INT < 23) {
        createDir();

    } else {
        final String[] PERMISSIONS_STORAGE = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        //Asking request Permissions
        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_STORAGE, 9);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    boolean writeAccepted = false;
    switch (requestCode) {
        case 9:
            writeAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
            break;
    }
    if (writeAccepted) {
        createDir();
    } else {
        Toast.makeText(MainActivity.this, "You don't assign permission.", Toast.LENGTH_LONG).show();
    }
}

private void createDir(){
    File file = new File(Environment.getExternalStorageDirectory() + File.separator + "OCR Documents");
    file.mkdirs();
    Toast.makeText(MainActivity.this, file.getAbsolutePath(), Toast.LENGTH_LONG).show();
}

您必须在活动正文中添加getWirtePermissionAndCreateDir()而不是writeFolder()

答案 2 :(得分:0)

以下功能将创建文件夹,然后在该文件夹中创建文件,如果文件夹已存在,则只需创建文件。

private FileOutputStream fos;

//Function: create a file in a folder
private boolean createFileInFolder(String fileName, String folderName) {
    if (isExternalStorageWritable()) {
        String path = Environment.getExternalStorageDirectory() + "/" + folderName;
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        txtFile = new File(path, fileName);
        try {
            fos = new FileOutputStream(txtFile);
            return true;
        } catch (IOException e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
            return false;
        }
    } else
        return false;
}

//Function: IsExternalStorageWritable?
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

您可能需要检查权限,然后定义这些功能。

private boolean permission;
private final int MY_PERMISSIONS_REQUEST = 10;

//Function: checkPermission
private void checkPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        // No explanation needed, we can request the permission.
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_PERMISSIONS_REQUEST);

    } else {
        permission = true;
    }

}

//Function: Permission Request Results
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                permission = true;
            } else {
                permission = false;
            }
            return;
        }
    }
}

在清单文件中,不要忘记添加此行。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />