英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论