输出SQLite database 到sd卡

本文介绍了一个用于将Android设备上的数据库文件导出到外部存储的任务类实现。该类使用了AsyncTask来处理后台的文件复制操作,并提供了成功或失败的反馈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


   
public static class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> { 
       
private Context ctx; 
 
       

       
public ExportDatabaseFileTask(Context ctx) { 
           
super(); 
           
this.ctx=ctx; 
       
} 
 
        
        protected Boolean doInBackground(final String... args) { 
 
           
File dbFile = 
                   
new File(Environment.getDataDirectory() + "/data/[com.your.pkg]/databases/[pkg]"); 
 
           
File exportDir = new File(Environment.getExternalStorageDirectory(), ""); 
           
if (!exportDir.exists()) { 
              exportDir
.mkdirs(); 
           
} 
           
File file = new File(exportDir, dbFile.getName()); 
 
           
try { 
              file
.createNewFile(); 
             
this.copyFile(dbFile, file); 
             
return true; 
           
} catch (IOException e) { 
             
Log.e("birthdroid", e.getMessage(), e); 
             
return false; 
           
} 
       
} 
 
       
        protected void onPostExecute(final Boolean success) { 
           
if (success) { 
             
Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show(); 
           
} else { 
             
Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show(); 
           
} 
       
} 
 
       
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(); 
           
} 
       
} 
 
     
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值