如何在Android中制作文件的副本?
在我的应用程序中,我想保存具有不同名称的某个文件的副本(我从用户那里获得)
我真的需要打开文件的内容并将其写入另一个文件吗?
最好的方法是什么?
在我的应用程序中,我想保存具有不同名称的某个文件的副本(我从用户那里获得)
我真的需要打开文件的内容并将其写入另一个文件吗?
最好的方法是什么?
要复制文件并将其保存到目标路径,您可以使用以下方法。
public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}
在 API 19+ 上,您可以使用 Java 自动资源管理:
public static void copy(File src, File dst) throws IOException {
try (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
或者,您可以使用 FileChannel 复制文件。复制大文件时,它可能比字节复制方法更快。但是,如果您的文件大于2GB,则无法使用它。
public void copy(File src, File dst) throws IOException {
FileInputStream inStream = new FileInputStream(src);
FileOutputStream outStream = new FileOutputStream(dst);
FileChannel inChannel = inStream.getChannel();
FileChannel outChannel = outStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inStream.close();
outStream.close();
}