我正在使用Android。我的要求是我有一个目录和一些文件,后来我将一些其他文件下载到另一个目录中,我的目的是将最新目录中的所有文件复制到第一个目录中。在将文件从最新文件复制到第一个目录之前,我需要从第一个目录中删除所有文件。
答案 0 :(得分:22)
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数据库的有用文章。
答案 1 :(得分:5)
Apache FileUtils非常简单而且很好......
包括Apache commons io package add commons-io.jar
或
commons-io android gradle dependancy
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();
}
答案 2 :(得分:1)
您还必须使用以下代码:
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();
}
}