[英]Move or copy .3gp files from one directory “External Dir” to another External directory in Android
[英]How to copy my files from one directory to another directory?
我正在使用Android。 我的要求是我有一个包含一些文件的目录,后来我将一些其他文件下载到另一个目录中,目的是将所有文件从最新目录复制到第一个目录中。 在将文件从最新复制到第一个目录之前,我需要从第一个目录中删除所有文件。
void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
我不记得在哪里找到它,但这是我用来备份SQLite数据库的有用文章。
Apache FileUtils做到这一点非常简单而且很好。
包括Apache commons io包, 添加commons-io.jar
要么
commons-io android gradle依赖
compile 'commons-io:commons-io:2.4'
添加此代码
String sourcePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TongueTwister/sourceFile.3gp";
File source = new File(sourcePath);
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TongueTwister/destFile.3gp";
File destination = new File(destinationPath);
try
{
FileUtils.copyFile(source, destination);
}
catch (IOException e)
{
e.printStackTrace();
}
您还必须使用以下代码:
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.