【发布时间】:2015-09-14 15:22:50
【问题描述】:
我的应用程序 (Android API 15) 制作一张图片并将其存储在内部存储器的文件夹中。现在,我想将此文件复制到外部存储中的另一个文件夹,例如/sdcard/myapp。我尝试了以下方法:
方法一:
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();
}
这些方法都不能解决我的任务。在检查了一些相关的主题,我发现唯一的建议是验证持久性
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在AndroidManifest.xml 中,它确实存在。
方法 #1 完成执行,但没有文件夹和文件被复制。
在方法#2中,应用程序失败,java.lang.NullPointerException outChannel = new FileOutputStream(dst).getChannel(); 出现异常,但对象 dst 不为空。
在方法#3中,我决定验证目标对象是否存在并在需要时创建一个文件夹,但是当我检查是否可以编写时,检查返回false。
我尝试了几种其他方法,成功创建了一个空文件夹,但没有真正复制任何文件。
由于这是我迈向 Android 的第一步,我觉得我错过了一些小事。请指出我,如何将文件从一个文件夹复制到 Android 中的另一个文件夹,包括从内部存储器移动到外部存储器的文件。
【问题讨论】:
-
可能是路径问题?
-
@Proxytype,关于路径,我是这样做的:
String dstPath = Environment.getExternalStorageDirectory() + File.separator + "myapp" + File.separator + "IMG_" + timeStamp + ".jpg"; File dst = new File(dstPath);。我的目标路径应该包含文件名还是仅包含文件夹?为什么new FileOutputStream(dst).getChannel();会返回 null,即使dst已满且存储空间有可用空间? -
在写入之前尝试创建目标文件,File dest = new File(path);检查它是否是在设备上创建的...也给它命名.. File to = new File(dst.getPath() + "/myname");
-
我已经这样做了,甚至更多:
if (!dst.exists()) {isCreated = dst.mkdir();},在此代码之后变量isCreated等于false。奇怪,为什么我可以创建初始文件,但不能将其复制到另一个文件夹,甚至无法创建文件夹。 -
内部路径是否包含数据目录?按照这个答案stackoverflow.com/questions/4751609/…
标签: java android file-io copy android-external-storage