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

时间:2017-12-20 13:34:14

标签: java android ioexception android-external-storage enoent

我在将文件写入外部存储目录时遇到问题。我添加了权限。某些设备的代码工作正常,而其他设备崩溃。我得到的错误是 java.io.IOException:open failed: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();
    }
}

1 个答案:

答案 0 :(得分:1)

尝试使用此

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