无法获取所选文件名的完整真实路径

ccgok5k5  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(716)

这个问题在这里已经有答案了

android kotlin:获取一个filenotfoundexception,其文件名是从文件选择器中选择的(3个答案)
android-获取从文件资源管理器中选择的.txt文件的实际路径(1个答案)
上个月关门了。
我没有获取当前路径var name“filepath”而是获取值e/file 路径:/document/29但我选择的文件存储在下载文件夹文件名是“test.xlsx”我需要原始路径文件名和文件扩展名传入fileinputstream()。我无法修复它…有人能给出代码吗
btnimport.setonclicklistener(新视图.onclicklistener(){

@Override
            public void onClick(View v) {
                Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
                fileintent.setType("*/*");
                try {
                    startActivityForResult(fileintent, requestcode);
                } catch (ActivityNotFoundException e) {
                    lbl.setText("No activity can handle picking a file. Showing alternatives.");
                }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        switch (requestCode) {
            case requestcode:
                String FilePath = data.getData().getPath();

                Log.e("File path", FilePath);

                if (FilePath.contains("/root_path"))
                    FilePath = FilePath.replace("/root_path", "");

                Log.e("New File path", FilePath);

                try {
                    if (resultCode == RESULT_OK) {
                        AssetManager am = this.getAssets();
                        InputStream inStream;
                        Workbook wb = null;

                        try {
                            inStream = new FileInputStream(FilePath);
                            Log.e("Extension",FilePath.substring(FilePath.lastIndexOf(".")));

                            if (FilePath.substring(FilePath.lastIndexOf(".")).equals(".xls")) {
                                Log.e("File Type", "Selected file is XLS");
                                wb = new HSSFWorkbook(inStream);
                            }
                            else if (FilePath.substring(FilePath.lastIndexOf(".")).equals(".xlsx")) {
                                Log.e("File Type", "Selected file is XLSX");
                                wb = new XSSFWorkbook(inStream);
                            }
                            else {
                                wb = null;
                                lbl.setText("Please select a valid Excel file");
                                return;

                            }

                            inStream.close();
h7appiyu

h7appiyu1#

使用它将返回文件的实际路径

public class FileUtils {

public static String getRealPath(Context context, Uri uri) {
    String realPath;
    realPath = FileUtils.getRealPath_API19(context, uri);
    return realPath;
}

@SuppressLint("NewApi")
public static String getRealPath_API19(final Context context, final Uri uri) {

    // DocumentProvider
    if (DocumentsContract.isDocumentUri(context, uri)) {

        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/"
                        + split[1];
            }
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"),
                    Long.parseLong(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection,
                    selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context
 *            The context.
 * @param uri
 *            The Uri to query.
 * @param selection
 *            (Optional) Filter used in the query.
 * @param selectionArgs
 *            (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri,
                                   String selection, String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = { column };

    try {
        cursor = context.getContentResolver().query(uri, projection,
                selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

/**
 * @param uri
 *            The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri
            .getAuthority());
}

/**
 * @param uri
 *            The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri
            .getAuthority());
}

/**
 * @param uri
 *            The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri
            .getAuthority());
}

/**
 * @param uri
 *            The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri
            .getAuthority());
}
}

像这样使用

String realPath = FileUtils.getRealPath(context, uri);

之后使用这个路径并创建新文件和文件的getrealname。

fwzugrvs

fwzugrvs2#

我需要具有文件扩展名的文件名的原始路径来传入fileinputstream()。
不,您不需要“真正的路径”,因为您最好使用获得的uri来打开输入流。

InputStream is = getContentResolver().openInputStream(data.getData());

像使用你想要的流一样使用它。

相关问题