Android FileNotFoundException的原因未知
我有一个方法:Android FileNotFoundException的原因未知,android,file,Android,File,我有一个方法:copyImage 这是在ImageLoder类中获取两个字符串参数(sourceimage,targetimage),如下所示: public Class ImageLoader{ public boolean copyIMAGE(String source, String target){ File sourceFile=new File(Environment.getExternalStorageDirectory()+source);
copyImage
这是在ImageLoder
类中获取两个字符串参数(sourceimage,targetimage),如下所示:
public Class ImageLoader{
public boolean copyIMAGE(String source, String target){
File sourceFile=new File(Environment.getExternalStorageDirectory()+source);
File targetFile=new File(Environment.getExternalStorageDirectory()+target);
InputStream fis;
OutputStream fos;
BufferedOutputStream bufferIS;
try{
fis=new FileInputStream(destinationFile);
fos=new FileOutputStream(targetFile);
bufferIS=new BufferedOutputStream(fos);
byte[] b=new byte[1024];
int len=0;
try
{
while ((len = fis.read(b)) != -1)
{
fos.write(len);
}
bufferIS.close();
fos.close();
fis.close();
return true;
}
catch (IOException e)
{
}
}catch(FileNotFoundException e){
}
return false;
}
}
在MainActivity类中单击copyButton后激发的方法,copyImage返回false
copyButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view)
{
// TODO: Implement this method
String source="/storage/emulated/0/Download/my image.jpeg";
String target ="/storage/emulated/0/Download//images/my image.jpeg";
loader.copyIMAGE(source,target);
}
});
方法返回false,我得到FileNotFound异常
Ps:源文件存在,
目的地存在,
我有rw权限。为什么要使用
环境。getExternalStorageDirectory()
?删除此项,因为源
和目标
已经是完整路径
File destinationFile=new File(source);
File targetFile=new File(target);
而且您的复制函数不正确,您正在使用错误的参数调用write
while ((len = fis.read(b)) != -1)
{
fos.write(b, 0, len);
}
哪个文件是例外?在catch块中打印堆栈跟踪。我不知道,因为我使用的是智能手机ide。为了进行调试,我使用Toast Messages,而不是将源文件称为destinationFile。非常混乱。应该以fos.close()结尾。还有fis.close()也不错。谢谢。我这样做了,文件被复制了,但似乎并不是所有字节都被复制了。目标文件已损坏