移动在Android上
问题描述:
我需要从一个位置上的用户SD卡将文件移动到另一个位置上的SD卡移动在Android上
目前,我与File.renameTo
例如这样一个文件从sdcard/test/one.txt到sdcard/test2/two.txt
某些用户报告文件移动功能不起作用。
How to copy files from 'assets' folder to sdcard?
那么什么是一个目录中的文件移动到另一个对SD卡的最佳方式:
我碰到下面的链接来了?
答
尝试复制这些代码并检查文件并删除原来的文件。
private void backup(File sourceFile)
{
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel in = null;
FileChannel out = null;
try
{
File backupFile = new File(backupDirectory.getAbsolutePath() + seprator + sourceFile.getName());
backupFile.createNewFile();
fis = new FileInputStream(sourceFile);
fos = new FileOutputStream(backupFile);
in = fis.getChannel();
out = fos.getChannel();
long size = in.size();
in.transferTo(0, size, out);
}
catch (Throwable e)
{
e.printStackTrace();
}
finally
{
try
{
if (fis != null)
fis.close();
}
catch (Throwable ignore)
{}
try
{
if (fos != null)
fos.close();
}
catch (Throwable ignore)
{}
try
{
if (in != null && in.isOpen())
in.close();
}
catch (Throwable ignore)
{}
try
{
if (out != null && out.isOpen())
out.close();
}
catch (Throwable ignore)
{}
}
}
答
为什么不能使用rename
?
File sd=Environment.getExternalStorageDirectory();
// File (or directory) to be moved
String sourcePath="/.Images/"+imageTitle;
File file = new File(sd,sourcePath);
// Destination directory
boolean success = file.renameTo(new File(sd, imageTitle));
答
我知道这个问题已经很久很久以前回答,但我发现拷贝整个文件是一个严酷的方法...... 这里是我做的,如果有人需要它:
static public boolean moveFile(String oldfilename, String newFolderPath, String newFilename) {
File folder = new File(newFolderPath);
if (!folder.exists())
folder.mkdirs();
File oldfile = new File(oldfilename);
File newFile = new File(newFolderPath, newFilename);
if (!newFile.exists())
try {
newFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return oldfile.renameTo(newFile);
}
感谢,那很好用 – user1177292 2012-02-03 22:29:46