错误在使用DocumentFile.createFile()在SD卡创建新的文件;(Error wh

2019-10-29 12:40发布

我试图创建SD卡上创建新的文件为Android 5.0及以上。 因此,首先,我让用户通过授予SAF权限。 这是怎么了检查所选目录是SD卡或不。

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

然后,这就是我想创建一个新的文件。

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

下面是我现在用得到DocumentFile为到该文件必须创建的目录的方法。

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

该代码工作正常的大部分时间,但有时我得到java.lang.NullPointerException

任何帮助将不胜感激。

编辑:这是我的FileUtil类

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


}

编辑2:

在该文件已被创建的路径是不错,我也检查了URI的权限,甚至是不为空。

值是

该文件具有路径是created- /storage/external_SD

许可URI- content://com.android.externalstorage.documents/tree/6634-3765%3A

编辑3:

我使用这个库找到SD卡路径。

Answer 1:

从继续这个答案现在你有DocumentFile (这是建立在它里面的文件的目录)通过循环只是使用myDocumentFile.createFile(...)对你的期望创建一个新的文件directory

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

然后流归这

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
防止findFile在空DocumentFile通过检查的价值rootDocFile在每次循环。 (发生在当用户选择错误的路径,而不是的sd-card

for (int i = 3; i < parts.length; i++)
{
    if (rootDocFile != null) {
        rootDocFile = rootDocFile.findFile(parts[i]);
    }
}


文章来源: Error while creating new File in SD Card using DocumentFile.createFile();