Error while creating new File in SD Card using Doc

2019-09-16 11:23发布

I am trying to create a new File in SD Card for Android 5.0 and above. So first I am making the user grant the permission through SAF. This is how I am check if the selected Directory is SD Card or Not.

public static boolean wrong_directory_selected(Uri uri, Context con)
    {

        final File uri_path=new File(FileUtil.getFullPathFromTreeUri(uri,con));
        if(uri_path.getName().toLowerCase().equals(new File("SD CARD PATH").getName().toLowerCase()))
        {

            return false;
        }
        return  true;
    }

And then this is how I am Trying to Create a new File.

DocumentFile move = DocumentFile(new File("path)).createFile(mime,"name); // But I am getting java.lang.NullPointerException 

Below are the methods which I am using to get the DocumentFile for the Directory to which the file has to be Created.

public static DocumentFile DocumentFile(final File file)
{

    DocumentFile rootDocFile = DocumentFile.fromTreeUri(con, permission().getUri());

    String[] parts = (file.getPath()).split("\\/");

    for (int i = 3; i < parts.length; i++)
    {

        rootDocFile = rootDocFile.findFile(parts[i]);

    }
    return rootDocFile;
}

public static UriPermission permission()
{
    for (UriPermission permissionUri : con.getContentResolver().getPersistedUriPermissions())
    {
        final File uri_path = new File(FileUtil.getFullPathFromTreeUri(permissionUri.getUri(), con));

        if (uri_path.getName().toLowerCase().equals(new File("SD_CARD_PATH").getName().toLowerCase()))
        {
            return permissionUri;

        }

    }

    return null;
}

The code is working fine most of the time but sometime I am getting java.lang.NullPointerException.

Any Help would be Grateful.

EDIT: This is my FileUtil class

public final class FileUtil {


    private static final String PRIMARY_VOLUME_NAME = "primary";




    @Nullable
    public static String getFullPathFromTreeUri(@Nullable final Uri treeUri, Context con) 
    {
        if (treeUri == null) 
        {
            return null;
        }
        String volumePath = FileUtil.getVolumePath(FileUtil.getVolumeIdFromTreeUri(treeUri),con);
        if (volumePath == null)
        {
            return File.separator;
        }
        if (volumePath.endsWith(File.separator))
        {
            volumePath = volumePath.substring(0, volumePath.length() - 1);
        }

        String documentPath = FileUtil.getDocumentPathFromTreeUri(treeUri);
        if (documentPath.endsWith(File.separator)) 
        {
            documentPath = documentPath.substring(0, documentPath.length() - 1);
        }

        if (documentPath.length() > 0)
        {
            if (documentPath.startsWith(File.separator)) 
            {
                return volumePath + documentPath;
            }
            else {
                return volumePath + File.separator + documentPath;
            }
        }
        else
        {
            return volumePath;
        }
    }


    private static String getVolumePath(final String volumeId, Context con)
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) 
        {
            return null;
        }

        try {
            StorageManager mStorageManager =
                    (StorageManager) con.getSystemService(Context.STORAGE_SERVICE);

            Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");

            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getUuid = storageVolumeClazz.getMethod("getUuid");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isPrimary = storageVolumeClazz.getMethod("isPrimary");
            Object result = getVolumeList.invoke(mStorageManager);

            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) 
            {
                Object storageVolumeElement = Array.get(result, i);
                String uuid = (String) getUuid.invoke(storageVolumeElement);
                Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement);

                // primary volume?
                if (primary && PRIMARY_VOLUME_NAME.equals(volumeId)) 
                {
                    return (String) getPath.invoke(storageVolumeElement);
                }

                // other volumes?
                if (uuid != null) 
                {
                    if (uuid.equals(volumeId)) 
                    {
                        return (String) getPath.invoke(storageVolumeElement);
                    }
                }
            }

            // not found.
            return null;
        }
        catch (Exception ex) 
        {
            return null;
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static String getVolumeIdFromTreeUri(final Uri treeUri) 
    {
        final String docId = DocumentsContract.getTreeDocumentId(treeUri);
        final String[] split = docId.split(":");

        if (split.length > 0)
        {
            return split[0];
        }
        else
        {
            return null;
        }
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static String getDocumentPathFromTreeUri(final Uri treeUri) 
    {
        final String docId = DocumentsContract.getTreeDocumentId(treeUri);
        final String[] split = docId.split(":");
        if ((split.length >= 2) && (split[1] != null))
        {
            return split[1];
        }
        else 
        {
            return File.separator;
        }
    }


}

EDIT 2 :

The Path in which the file has to be created is fine and I have also checked the Permission URI and even that is not null.

The Values are

The path where the file has to be created- /storage/external_SD

Permission Uri- content://com.android.externalstorage.documents/tree/6634-3765%3A

EDIT 3:

I am using this library to find the SD Card path.

1条回答
Fickle 薄情
2楼-- · 2019-09-16 11:52

Continue from this answer now that you have the DocumentFile (which is a directory to create a file inside it) through the loop just use myDocumentFile.createFile(...) to create a new file on your desired directory.

// creating the file
DocumentFile documentFileNewFile = documentFileGoal.createFile(myMimeType,
myNewFileName);

Then stream to it

outputStream = getContentResolver().openOutputStream(documentFileNewFile.getUri());
inputStream = new FileInputStream(myInputFile);

...
   if (outputStream != null) {
       byte[] buffer = new byte[1024];
       int read;
       while ((read = inputStream.read(buffer)) != -1) {
           outputStream.write(buffer, 0, read);
       }
      }
...
...
...
} finally {
         if (inputStream != null)
             inputStream.close();
         if (outputStream != null) {
             outputStream.flush();
             outputStream.close();
           }
         }  

Edite
Prevent findFile on a null DocumentFile by checking the value of rootDocFile on each loop. (happens when the user selects a wrong path instead of the sd-card)

for (int i = 3; i < parts.length; i++)
{
    if (rootDocFile != null) {
        rootDocFile = rootDocFile.findFile(parts[i]);
    }
}
查看更多
登录 后发表回答