2017-02-21 147 views
-2

为什么它不起作用? 编辑:增加了新的代码版本&日志:如何通过Uri复制JPG文件

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做了预览照片。

+1

在catch中添加一些日志,你会看到发生了什么 – Selvin

+0

捕获异常并忽略它是非常糟糕的。 –

+0

@Selvin我们需要知道什么? – Nikita

回答

0

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

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); 
    } 

与上面的代码比较你的代码,没有用于传输数据,虽然这里没有使用方法的差异。