在我的应用程序中,我想用用户提供的不同名称保存某个文件的副本。
我真的需要打开文件内容并将其写入另一个文件吗?
有什么最好的方法来实现这一点?
要复制文件并保存到目标路径,您可以使用以下方法。
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();
}
FileOutputStream outStream = new FileOutputStream(dst);
步骤中出现了异常java.io.FileNotFoundException: /sdcard/AppProj/IMG_20150626_214946.jpg: open failed: ENOENT (No such file or directory)
。根据文本,我意识到文件不存在,所以我检查并调用dst.mkdir();
(如果需要),但仍然没有帮助。我还尝试检查dst.canWrite();
,它返回了false
。这可能是问题的源吗?是的,我有<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
。 - Miketry ( FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst) ) {
- AlbertMarkovskionProgressUpdate
,以便我可以在 ProgressBar 中显示它?在被接受的解决方案中,我可以在 while 循环中计算进度,但我不知道如何在这里做到这一点。 - George BezerraKotlin 的扩展
fun File.copyTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
contentResolver.openInputStream(uri)
打开的URI。 - charles-allen在安卓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());
}
这些对我来说效果很好
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
File("originalFileDir", "originalFile.name")
.copyTo(File("newFileDir", "newFile.name"), true)
true
或false
用于覆盖目标文件
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/copy-to.html
可能已经为答案太晚了,但最方便的方法是使用
FileUtils
的
static void copyFile(File srcFile, File 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 中,只需:
val fileSrc : File = File("srcPath")
val fileDest : File = File("destPath")
fileSrc.copyTo(fileDest)
这里有一个解决方案,如果在复制过程中发生错误,它实际上会关闭输入/输出流。此解决方案利用了Apache Commons IO IOUtils方法来进行复制和处理流的关闭。
public void copyFile(File src, File dst) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dst);
IOUtils.copy(in, out);
} catch (IOException ioe) {
Log.e(LOGTAG, "IOException occurred.", ioe);
} finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
}
}
// 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)
这适用于任何像图片和视频这样的文件