【问题标题】:How to copy a JPG file via Uri如何通过 Uri 复制 JPG 文件
【发布时间】:2017-02-21 09:41:33
【问题描述】:

为什么它不起作用? 编辑:添加了新版本的代码和日志:

    private void savePhotoFromCacheToFolder(Uri uri) {

    File goodPhoto = album.setUpPhotoFile(); //new empty JPG
    File currentPhoto = new File(uri.getPath()); //JPG from camera in cache

    Log.v(TAG, "\ngoodPhoto Path " + goodPhoto);
    Log.v(TAG, "\ncurrentPhoto Path " + currentPhoto);

    FileInputStream source = null;
    FileOutputStream destination = null;

    try {
        source = new FileInputStream(currentPhoto);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.v(TAG, "\ncurrentPhoto not found ");
    }

    try {
        destination = new FileOutputStream(goodPhoto);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.v(TAG, "\ngoodPhoto not found  ");
    }

    FileChannel sourceFileChannel = source.getChannel();
    FileChannel destinationFileChannel = destination.getChannel();

    long size = 0;
    try {
        size = sourceFileChannel.size();
        sourceFileChannel.transferTo(0, size, destinationFileChannel);
    } catch (IOException e) {
        e.printStackTrace();
        Log.v(TAG, "\nshit happens ");
    }

}

日志:

V/MainActivity: goodPhoto Path /storage/emulated/0/Pictures/Good photos/IMG_20170222_113700_-913025224.jpg
V/MainActivity: currentPhoto Path /cache/photo.jpg
V/MainActivity: currentPhoto not found 
java.lang.NullPointerException: Attempt to invoke virtual method 'java.nio.channels.FileChannel java.io.FileInputStream.getChannel()' on a null object reference

看起来 Uri 不正确,但此 Uri 是由相机应用返回的。或者我可能无法访问缓存文件夹,但之前我确实使用这个 Uri 预览了照片。

【问题讨论】:

  • 添加一些登录catch,你会看到发生了什么
  • 捕获异常并忽略它是非常糟糕的。
  • @Selvin 我们需要知道什么?
  • catch 中添加日志并记录异常(如果有)。
  • 我不知道这是多么合法,但这是可行的source = (FileInputStream) UriHelper.openInputStream(this, uri);

标签: android file


【解决方案1】:

我们已经创建了一个输入流和一个输出流对象。输入流指向当前的java文件,输出流指向Output.java。我们希望将文件的内容传输到这个 Output.java。如前所述,文件对象与文件通道对象相关联。因此,我们使用以下代码获取输入和输出流的 File Channel 对象,

public copyFile( String filePath ){


        FileInputStream source = new FileInputStream(filePath );
        FileOutputStream destination = new FileOutputStream("Output.java");

        FileChannel sourceFileChannel = source.getChannel();
        FileChannel destinationFileChannel = destination.getChannel();

        long size = sourceFileChannel.size();
        sourceFileChannel.transferTo(0, size, destinationFileChannel);
    }

将你的代码和上面的代码比较一下,传输数据的方法是不同的,这里没有使用while。

【讨论】:

    猜你喜欢
    • 2019-12-30
    • 2023-03-26
    • 2020-01-13
    • 2018-01-12
    • 2018-10-03
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    相关资源
    最近更新 更多