在我的应用程序中,我想用不同的名称保存某个文件的副本(这是我从用户处获得的)
我真的需要打开文件的内容并将其写入另一个文件吗?
最好的方法是什么?
发布于 2012-02-15 20:59:04
要复制文件并将其保存到目标路径,您可以使用以下方法。
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();
}
}
在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);
}
}
}
}
发布于 2017-09-21 20:39:50
它的Kotlin扩展
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
发布于 2017-12-16 15:00:11
这在Android O (API 26)上很简单,如您所见:
@RequiresApi(api = Build.VERSION_CODES.O)
public static void copy(File origin, File dest) throws IOException {
Files.copy(origin.toPath(), dest.toPath());
}
https://stackoverflow.com/questions/9292954
复制相似问题