覆盖一个非文本文件以替换另一个

huangapple go评论97阅读模式
英文:

Overwriting a non-text file with another

问题

我不确定如何覆盖非文本文件。如何用默认的 default.db 文件覆盖我的 main.db 文件(sqlite 3)?

private void yesAction() {

    try {

        String text = Files.readString(Paths.get("src\\main\\database\\default.db"));

        System.out.println(text);

        Files.writeString(Paths.get("src\\main\\database\\main.db"), text, Charset.defaultCharset());

    } catch (IOException e) {

        e.printStackTrace();
    }
}
英文:

I am not sure how to overwrite non-text files. How can I overwrite my main.db file (sqlite 3) with my default.db file?

private void yesAction() {

    try {

        String text = Files.readString(Paths.get("src\\main\\database\\default.db"));

        System.out.println(text);

        Files.writeString(Paths.get("src\\main\\database\\main.db"), text, Charset.defaultCharset());

    } catch (IOException e) {

        e.printStackTrace();
    }
}

答案1

得分: 2

你可以使用这个FileChannel来覆盖数据库文件或任何其他文件。

try {
    File oldDb = new File(old, oldDbPath);
    File newDb = new File(new, newDbPath);

    if (newDb.exists()) {
        FileChannel oldDbChannel = new FileInputStream(oldDb).getChannel();
        FileChannel newDbChannel = new FileOutputStream(newDb).getChannel();
        newDbChannel.transferFrom(oldDbChannel, 0, oldDbChannel.size());
        oldDbChannel.close();
        newDbChannel.close();
    }

} catch (Exception e) {
    e.printStackTrace();
}

你可以在这里了解更多关于FileChannel的信息:https://developer.android.com/reference/java/nio/channels/FileChannel。

英文:

You can overwrite db files or any other file using this FileChannel.

try {
    File oldDb = new File(old, oldDbPath);
    File newDb = new File(new, newDbPath);

    if (newDb.exists()) {
        FileChannel oldDbChannel = new FileInputStream(oldDb).getChannel();
        FileChannel newDbChannel = new FileOutputStream(newDb).getChannel();
        newDbChannel.transferFrom(oldDbChannel, 0, oldDbChannel.size());
        oldDbChannel.close();
        newDbChannel.close();
    }

} catch (Exception e) {
    e.printStackTrace();
}

You can read more about FileChannel here https://developer.android.com/reference/java/nio/channels/FileChannel.

huangapple
  • 本文由 发表于 2020年8月12日 04:26:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63365895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定