【问题标题】:Copying a File?复制文件?
【发布时间】:2018-10-03 07:41:49
【问题描述】:

我找到了一个可爱的功能,可以将我的数据库文件从原始路径复制到外部存储卡:

public static void copyFile(File src, File dst) throws IOException {
        if(!dst.exists()) {
            dst.createNewFile();
        }
        else{
            dst.delete();
            dst.createNewFile();
        }
        InputStream in = new FileInputStream(src);
        try {
            OutputStream out = new FileOutputStream(dst);
            try {
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }

但我无法调用该函数,这里是我的代码在一个简单的按钮上:

exportDatabase.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(Info.this, getDatabasePath(Info.this, "Library.sqlite"), Toast.LENGTH_SHORT).show();
        File srcFile = new File(getDatabasePath(Info.this, "Library.sqlite"));
        File dstFile = new File((getExternalStorageDirectory() + "/Library.sqlite"));
        copyFile(srcFile, dstFile);
    }
});

这行代码copyFile(srcFile, dstFile); 被标记为错误。在鼠标悬停时,我收到 Unhandled Exeption:java.IO.IOExeption

如何正确调用?

编辑: 补全缺失的代码,这里是按钮中用到的函数:

public String getDatabasePath(Context context,String databaseName)
{
    return context.getDatabasePath(databaseName).getAbsolutePath();
}
public String getExternalStorageDirectory() {
    String externalStorageDirectory;
    externalStorageDirectory = Environment.getExternalStorageDirectory().toString();
    return externalStorageDirectory;
}

我刚刚在 Memu(android 模拟器)中测试了我的解决方案,并且代码非常棒!我现在能够备份和恢复我的 SQLite 数据库。 (恢复简单的反转 dst 和 src 文件路径)。希望这会有所帮助。谢谢大家。

【问题讨论】:

    标签: android file io copy


    【解决方案1】:

    这行代码copyFile(srcFile, dstFile);被标记为错误。在鼠标悬停时,我收到 Unhandled Exeption:java.IO.IOExeption

    是的,它的行为符合预期。 因为您的 copy() 方法可能会抛出 java.IO.IOExeption

    在这里阅读What throws an IOException

    您需要通过try-catch 发出声音来处理Exception

    试试这个

    try {
         copy(srcFile, dstFile);
     } catch (IOException e) {
         e.printStackTrace();
     }
    

    【讨论】:

    • 谢谢,太完美了!
    【解决方案2】:

    既然你这么说throws IOException, 您应该使用 catch 捕获异常。即将您的代码包装在 tr-catch 块中,如下所示

    try{
        copyFile(srcFile, dstFile);
    }
    catch(IOException e){
        e.printStackTrace();
    }
    

    【讨论】:

    • 谢谢,完美!
    【解决方案3】:

    您没有处理可能的Exception。将其包裹在 try-catch 中,例如

    try {
        copyFile(srcFile, dstFile);
    } catch (IOException e) {
        // handle it
    }
    

    【讨论】:

    • 谢谢,完美!
    猜你喜欢
    • 2016-12-19
    • 2018-07-27
    • 2014-08-30
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多