简体   繁体   English

从Uri创建文件发生异常

[英]Create file from Uri exception occurs

While creating a file from Uri and exception Occured. 从Uri创建文件时发生异常。 The value of exception shows null. exception的值显示为null。

try {
File mFile = new File(new URI(mediaUri.toString()));
data = readFile(mFile);     
 } catch (Exception e) {
Log.e("Error", e.getLocalizedMessage());
}   

Please help 请帮忙

Thanks in advance. 提前致谢。

The issue was while creating file from uri 问题是从uri创建文件时

File mFile = new File(new URI(mediaUri.toString())); 文件mFile =新文件(新URI(mediaUri.toString()));

The mediaUri.toString() was not returning the correct path of the video file from to get the correct path of the video file mediaUri.toString()并未从中返回视频文件的正确路径以获取视频文件的正确路径

File mFile = new File(new URI(getRealPathFromURI(contentUri));


     public String getRealPathFromURI(Uri contentUri) {

    String[] proj = { MediaStore.Video.Media.DATA };
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

This answer is userfull while fetching the video file path from the given Uri 从给定的Uri提取视频文件路径时,此答案是userfull

The problem is, that uri.toString() makes string of device (file:) and path itself. 问题在于,uri.toString()生成设备字符串(文件:)和路径本身。 You should use uri.getPath() instead. 您应该改用uri.getPath()。 This returns not Path, but String though. 返回的不是Path,而是String。 With maybe extra / or \\ at start. 开始时可能带有额外的/或\\。 You should give it off so that it would work on all systems. 您应该放开它,以便它在所有系统上都可以使用。 The correct and OS-independent line will be: 正确且独立于操作系统的行将是:

File mFile = new File(new Path(mediaUri.getPath()).toString);

Works on our project on win, mac, linux. 在Win,Mac,Linux上可以在我们的项目上工作。

A couple of things could be wrong. 有几件事可能是错误的。

First, mediaUri could be null 首先,mediaUri可以为null

Second, is readFile your own method(I guess it is), then you should either post the method or do your try/catch in readFile. 其次,readFile是您自己的方法(我想是),那么您应该发布该方法或在readFile中进行尝试/捕获。
The reason is this. 原因是这样的。 If I am to go by your code, you are creating a new file that should not contain any data, so what are you using readFile for? 如果要按您的代码进行操作,您正在创建一个不应包含任何数据的新文件,那么将readFile用于什么呢? If the file exists, and mediaUri is not null, then the null exception is from your readFile method. 如果文件存在,并且mediaUri不为null,则null异常来自您的readFile方法。

You should check mediaURI were corrected file path, I suppose it's not corrected file path. 您应该检查mediaURI是否已更正文件路径,我想它不是已更正文件路径。

Could you please explain a bit more??? 您能再解释一下吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM