在我的应用程序中,我想用不同的名称保存某个文件的副本(这是我从用户那里得到的)
我真的需要打开文件的内容并将其写入另一个文件吗?
最好的方法是什么?
在我的应用程序中,我想用不同的名称保存某个文件的副本(这是我从用户那里得到的)
我真的需要打开文件的内容并将其写入另一个文件吗?
最好的方法是什么?
当前回答
在Kotlin:很短的路
// fromPath : Path the file you want to copy
// toPath : The path where you want to save the file
// fileName : name of the file that you want to copy
// newFileName: New name for the copied file (you can put the fileName too instead of put a new name)
val toPathF = File(toPath)
if (!toPathF.exists()) {
path.mkdir()
}
File(fromPath, fileName).copyTo(File(toPath, fileName), replace)
这适用于任何文件,如图像和视频
其他回答
在kotlin中你可以用
file1.copyTo(file2)
file1是原始文件的对象,而file2是要复制到的新文件的对象
Kotlin扩展它
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
这在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());
}
现在回答可能太迟了,但最方便的方法是使用
FileUtils's
文件srcFile,文件destFile
这就是我所做的
`
private String copy(String original, int copyNumber){
String copy_path = path + "_copy" + copyNumber;
try {
FileUtils.copyFile(new File(path), new File(copy_path));
return copy_path;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
`
在Kotlin:很短的路
// fromPath : Path the file you want to copy
// toPath : The path where you want to save the file
// fileName : name of the file that you want to copy
// newFileName: New name for the copied file (you can put the fileName too instead of put a new name)
val toPathF = File(toPath)
if (!toPathF.exists()) {
path.mkdir()
}
File(fromPath, fileName).copyTo(File(toPath, fileName), replace)
这适用于任何文件,如图像和视频