英文:
How to stop file writer from overwriting text that already exists inside the document? Java
问题
如标题所示,我有一个文件写入器,我想多次重用该程序,并将文本保存到同一文本文档的新行中。
代码:
try {
File password1 = new File("password.txt");
if (password1.createNewFile()) {
System.out.println("文件已创建:" + password1.getName()); //创建新文件并输入变量
} else {
System.out.println("文件已存在:");
}
} catch (IOException e) {
System.out.println("发生错误。");
e.printStackTrace();
}
if (save) {
try {
FileWriter myWriter = new FileWriter("password.txt"); //将新创建的文件保存为txt
myWriter.write(web + ": " + password);
myWriter.close();
System.out.println("成功写入文件");
} catch (IOException e) {
System.out.println("发生错误");
e.printStackTrace();
}
}
英文:
So as the title says, I have a file writer and I want to reuse the program multiple times and saving the text onto a new line in the same text document.
Code:
try {
File password1 = new File("password.txt");
if (password1.createNewFile()) {
System.out.println("File created: " + password1.getName()); //Creates new file and inputs variables
} else {
System.out.println("File already exists:");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
if (save) {
try {
FileWriter myWriter = new FileWriter("password.txt"); //Saves newly created file as a txt
myWriter.write(web + ": " + password);
myWriter.close();
System.out.println("Successfully wrote to the file");
} catch (IOException e) {
System.out.println("An error occurred");
e.printStackTrace();
}
}
答案1
得分: 0
> FileWriter(File file, boolean append): 使用指定的 File 对象创建 FileWriter 对象。
> 如果第二个参数为 true,则会将字节写入文件末尾,而不是开头。
> 如果文件存在但是是一个目录而不是常规文件、或者文件不存在但无法创建、或者由于其他任何原因无法打开,就会抛出 IOException 异常。
你需要在构造函数中添加第二个参数以启用追加模式:
FileWriter myWriter = new FileWriter("password.txt", true);
英文:
> FileWriter(File file, boolean append): Creates a FileWriter object
> using specified File object. If the second argument is true, then
> bytes will be written to the end of the file rather than the
> beginning. It throws an IOException if the file exists but is a
> directory rather than a regular file or does not exist but cannot be
> created, or cannot be opened for any other reason
you need to add second parameter to your constructor to enable the append mode:
FileWriter myWriter = new FileWriter("password.txt", true);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论