如何写入和读取所有设备的外部存储目录?

How do I write to and read from External Storage directory of all devices?

我在将文件写入外部存储目录时遇到问题。我已经添加了权限。该代码在某些设备上运行良好,但在其他设备上会崩溃。我得到的错误是 java.io.IOException:打开失败:ENOENT(没有这样的文件或目录)。我希望每个设备和每个 Android 版本都 运行 此代码并根据需要将文件保存到外部存储。

代码如下:

    public void createFile(View v) {
        requestPermission();
        String fileLocation = Environment.getExternalStorageDirectory().getPath() + "/SavedFiles";
        String fileContent = getFileContent();
        //Check for samsung devices because they require a different method of storage access
        if(android.os.Build.DEVICE.contains("Samsung") || android.os.Build.MANUFACTURER.contains("Samsung")){
            fileLocation = fileLocation + "/external_sd/";
        }
        try {
            File file = new File(fileLocation, "newfile.txt");
            if (!file.exists()) {
                file.createNewFile();
                FileOutputStream fOut = new FileOutputStream(file);
                OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                myOutWriter.append(fileContent);
                myOutWriter.close();
                fOut.close();
                Toast.makeText(this, "File created!", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Could not create the file.", Toast.LENGTH_LONG).show();
        }
    }

public void requestPermission(){
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
        } else {
            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }
    else {
        Log.v(TAG,"Permission is granted");
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        createFile();
    }
}

尝试用这个替换您的代码

File fileDirectory = new File(Environment.getExternalStorageDirectory() + "/SavedFiles", "");
    if (!fileDirectory.exists())
            {
                fileDirectory.mkdirs();
            }
    File file = new File(fileDirectory, "newfile.txt");