簡體   English   中英

在不創建新文件的情況下處理 Uri

[英]Handle Uri without creating a new file

我正在使用的庫需要我傳遞一個文件路徑。

目前,我使用 Uri 創建一個新文件(在AsyncTask中),如下所示:

@Override
protected String doInBackground(Uri... params) {
    File file = null;
    int size = -1;
    try {
        try {
            if (returnCursor != null && returnCursor.moveToFirst()){
                int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                size = (int) returnCursor.getLong(sizeIndex);
            }
        }
        finally {
            if (returnCursor != null)
            returnCursor.close();
        }

        if (extension == null){
            pathPlusName = folder + "/" + filename;
            file = new File(folder + "/" + filename);
        }else {
            pathPlusName = folder + "/" + filename + "." + extension;
            file = new File(folder + "/" + filename + "." + extension);
        }

        BufferedInputStream bis = new BufferedInputStream(is);
        FileOutputStream fos = new FileOutputStream(file);

        byte[] data = new byte[1024];
        long total = 0;
        int count;
        while ((count = bis.read(data)) != -1) {
            if (!isCancelled()) {
                total += count;
                if (size != -1) {
                    publishProgress((int) ((total * 100) / size));
                }
                fos.write(data, 0, count);
            }
        }
        fos.flush();
        fos.close();

    } catch (IOException e) {
        errorReason = e.getMessage();
    }
    return file.getAbsolutePath();
}

可以想象,這可能需要一些時間,具體取決於文件大小。

問題

有什么方法可以訪問文件而無需創建/復制它?

*我讀過我可以使用ContentResolveropenInputStream()openOutputStream()等方法。 但這只會為我提供 stream 並且不能解決我必須編寫新文件的問題?


額外信息:

我通過將以下內容傳遞給 Intent 來獲取 Uri:

intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);

然后在onActivityResult我通過調用data.getData()來獲取 Uri。


請不要為我提供這樣的解決方案。 我不想從內容 Uri 中獲取文件 Uri,因為它不可靠且不正確。

很明顯,如果您只有內容方案,則無法處理內容方案的庫是沒有用的。

您必須復制文件中的內容。 就像你現在做的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM