2011-08-22 42 views
2

我试图从我的应用程序文件夹复制到另一个SD卡上的Android数据库文件。从DDMS文件浏览器我可以注意到,复制的文件大小为0.这是我的代码下面。复制Android数据库文件为空

public boolean copyDBFile(){ 
    File dbFile =new File(Environment.getDataDirectory() + DB_PATH); 
    File exportDir = new File(Environment.getExternalStorageDirectory() 
     + "/BACKUP_DIR"); 
    if (!exportDir.exists()) { 
     exportDir.mkdirs(); 
    } 

    File file = new File(exportDir, dbFile.getName()); 
    try { 
     file.createNewFile();   
     copyFile(dbFile, file); 
     return true; 
    } catch (IOException e) {  
     return false; 
    } 
} 


public 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(); 
    } 
} 

是否是一个许可问题?感谢帮助。

+3

你应该*总是*有一个catch语句为每个try语句,否则你不能说如果发生异常。在这里,添加一个catch到copyFile中的try。 – Snicolas

+0

你能解释一下吗?我认为他不想抓住例外,只是关闭渠道以避免泄漏。你的意思是它被自动捕获?如果是,那么我认为你已经解决了这个问题:) – MozenRath

+0

数据库文件没有被复制。只是一个同名的0号文件。看起来像文件被创建,但从不复制。 –

回答

1

@piyush 感谢的try/catch通知之前尝试使用outChannel.force(true);。在catch块中添加boolean copyDBFile()方法中的日志跟踪后发现错误。

public boolean copyDBFile(){ 
File dbFile =new File(Environment.getDataDirectory() + DB_PATH); 
File exportDir = new File(Environment.getExternalStorageDirectory() 
    + "/BACKUP_DIR"); 
if (!exportDir.exists()) { 
    exportDir.mkdirs(); 
} 

File file = new File(exportDir, dbFile.getName()); 
try { 
    file.createNewFile();   
    copyFile(dbFile, file); 
    return true; 
} catch (IOException e) { 
    Log.e("Sarelo", "Error creating file", e); 
    return false; 
} 

}

DB_PATH已经被设置为/data/data/package/databases/data.db,并添加到Environment.getDataDirectory()dbFile结果/data/data/data/package/databases/data.db 这是一个大错误!感谢所有的帮助:)

+0

aaargh!:)欢迎您,并且请将答案和评论投给plz :) – MozenRath

0

使用transferTo(...);

+0

:(还没有工作,db文件大小仍然是0. –

+2

你尝试过添加一个catch块并抛出一个异常吗?试着看看是否有一个异常被抛出,但由于catch块 – MozenRath

+0

你可以在添加catch块后显示你的代码吗? – MozenRath