【问题标题】:File not found exception when fetching the video path from Intent delivered to onActivityResult()从传递到 onActivityResult() 的 Intent 获取视频路径时找不到文件异常
【发布时间】:2018-05-03 18:41:53
【问题描述】:

我是 android 编程新手,需要帮助解决我在捕获视频文件并将其上传到服务器时遇到的这个问题。 我的活动 1 从使用原生视频捕获开始 -

private void recordVideo(){
    Intent takeVideoIntent = new 
    Intent(MediaStore.ACTION_VIDEO_CAPTURE);

    if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
    Uri videoUri = intent.getData();
    mVideoView.setVideoURI(videoUri);
    Log.d("Getting video path ", videoUri.getPath() );
  }
}

我通过将意图传递给活动 2 来上传到服务器。但是,在将文件上传到服务器时,我的应用程序崩溃了,因为我的 File 对象无法获取文件路径。 我正在记录的文件路径示例是 - /external/video/media/18518。 我没有使用任何外部存储,当我浏览我正在使用文件浏览器测试它的 Lenovo K4 笔记时,该文件不存在于

/external/video/media 目录。相反,视频被存储在

"/Internal Storage/DCIM/Camera/test.mp4"

作为一种解决方法,我在我的活动 2 代码中硬编码了这个文件路径,它正在读取文件并将其上传到服务器,但仍然得到文件未找到异常 -

            int readedBytes;
            byte[] buf = new byte[1024];
            File file = new File("/Internal Storage/DCIM/Camera/test.mp4");
            InputStream insputStream = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            long length = file.length();
            byte[] bytes = new byte[(int) length];
            insputStream.read(bytes);
            while((readedBytes = insputStream.read(buf)) >0 ){
                bos.write(buf, 0, readedBytes);
            }
            insputStream.close();


java.io.FileNotFoundException: /Internal Storage/DCIM/Camera/test.mp4: open failed: ENOENT (No such file or directory)
05-04 00:06:14.432 23628-24496/com.example.jayant.healthapp W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:496)
05-04 00:06:14.433 23628-24496/com.example.jayant.healthapp W/System.err:     at java.io.FileInputStream.<init>(FileInputStream.java:76)

这个问题的任何指针都会有很大的帮助。

【问题讨论】:

    标签: android


    【解决方案1】:

    但是,在将文件上传到服务器时,我的应用程序崩溃了,因为我的 File 对象无法获取文件路径。

    您没有得到文件。你得到一个UriUri 不是文件。特别是,您获得的Uri 具有content 方案,它可以指向相机应用程序希望它指向的任何内容。

    使用ContentResolveropenInputStream()Uri 标识的内容上获得InputStream

    我在我的活动 2 代码中硬编码了这个文件路径

    这不是任何 Android 设备上的有效文件路径。

    相反,视频被存储在“/Internal Storage/DCIM/Camera/test.mp4”中

    不,不是。您似乎将某些文件管理器可能报告的内容与 Android 设备本身实际使用的内容混淆了。

    使用Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) 获取设备自己的文件系统路径,该路径应映射到您看到的DCIM/ 目录。

    【讨论】:

    • 抱歉回复晚了,但感谢您的解决方案,它成功了!
    猜你喜欢
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多