编程语言
首页 > 编程语言> > java – 从URI或原始文件路径重新创建文件时文件长度为0 [getExternalFilesDir(String type)vs getFilesDir()]

java – 从URI或原始文件路径重新创建文件时文件长度为0 [getExternalFilesDir(String type)vs getFilesDir()]

作者:互联网

首先是一些背景:这个应用程序拍照并上传到Azure blob存储.

使用getApplicationContext()将图片存储在文件(内部存储器)中.getFilesDir();

要上传,我需要调用uploadFromFile(..)函数,如下所示:
CloudBlockBlob.uploadFromFile(String path);

Azure SDK的uploadFromFile函数如下所示:

public void uploadFromFile(final String path) throws StorageException, IOException {
        uploadFromFile(path, null /* accessCondition */, null /* options */, null /* opContext */);
    }

public void uploadFromFile(final String path, final AccessCondition accessCondition, BlobRequestOptions options,
            OperationContext opContext) throws StorageException, IOException {
        File file = new File(path);
        long fileLength = file.length();
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        this.upload(inputStream, fileLength, accessCondition, options, opContext);
        inputStream.close();
    }

问题是在长行fileLength = file.length(); fileLength为0的位置.

我已经使用Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)对此进行了测试;对于存储目录.这有效.

我需要使用内部存储与外部存储,因为这是该项目特别需要的.

编辑:Android File文档没有提到这种行为.我假设这可能与使用应用程序内部存储有关.

编辑:添加一些代码

我正在向我的相机意图发送一个File mPhotoFile.这将包含照片. mPhotoFileUri包含此文件的URI.以下是使用文件路径的代码.

File file = new File(mPhotoFile.getPath()); // value -> /data/user/0/com.example.devpactapp/files/JPEG_20160209_234929_1936823724.jpg
boolean fileExists = file.exists();         // true
long fileLength = file.length();            // length 0

以下是从URI获取文件的代码.

File file = new File(mPhotoFileUri.getPath());  // value -> /data/user/0/com.example.devpactapp/files/JPEG_20160209_235534_-1059496729.jpg
boolean fileExists = file.exists();             // true
long fileLength = file.length();                // length 0

我必须将此文件的路径传递给uploadFromFile函数.

我的’回答’中提到的解决方法.

解决方法:

即使我没有所有的信息,我也会打电话给你提供的路径中缺少文件. javadoc for length()特别提到这种情况将返回0.

因此,在对文件执行任何操作之前,请尝试检查exists().

标签:java,android,azure-blob-storage
来源: https://codeday.me/bug/20190706/1396698.html