我的应用程序( Android API 15
)制作图片并将其存储在内部存储器的文件夹中。现在,我想将此文件复制到外部存储中的另一个文件夹,例如/sdcard/myapp。我尝试了以下方法:
方法1:
private void copyFile(File src, File dst) throws IOException {
File from = new File(src.getPath());
File to = new File(dst.getPath());
from.renameTo(to);
}
方法2:
private void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(dst).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
方法3:
private void copyFile(File src, File dst) throws IOException {
FileInputStream inStream = new FileInputStream(src);
if (!dst.exists()) {
dst.mkdir();
}
if (!dst.canWrite()) {
System.out.print("CAN'T WRITE");
return;
}
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
}
这些方法都不能解决我的任务。在检查了许多相关主题之后,我发现的唯一建议是验证
在AndroidManifest.xml和它确实存在。
该 方法#1 完成执行,但没有文件夹和文件被复制。
在 方法#2 ,应用程序失败,异常java.lang.NullPointerException的outChannel = new
FileOutputStream(dst).getChannel();,但对象DST是不是空。
在 方法3中 ,我决定验证目标对象是否存在,并在需要时创建一个文件夹,但是当我检查是否可以写时,检查返回false。
我尝试了几种其他方法,这些方法成功创建了一个空文件夹,但实际上没有文件被复制。
由于这是我迈向Android的第一步,因此我觉得我错过了一些小事情。请指出我,如何将文件从一个文件夹复制到Android中的另一个文件夹,包括文件从内部存储器移动到外部存储器。