如何在java中打开文件而不删除其内容?
我希望我的程序为用户创建一个文件(只是第一次)并向其中写入一些信息(它不仅是一行,而且可以在以后随时进行调整)。所以我这样做了:如何在java中打开文件而不删除其内容?,java,file,io,java-io,formatter,Java,File,Io,Java Io,Formatter,我希望我的程序为用户创建一个文件(只是第一次)并向其中写入一些信息(它不仅是一行,而且可以在以后随时进行调整)。所以我这样做了: public void write() { try { file = new File("c:\\Users\\Me\\Desktop\\text.txt"); if(!file.exists()) // I found this somewhere on the in
public void write() {
try {
file = new File("c:\\Users\\Me\\Desktop\\text.txt");
if(!file.exists()) // I found this somewhere on the internet for File class
file.createNewFile(); // not to remove contents. I have no idea if it works
writer = new Formatter(file);
} catch(Exception e) {
e.printStackTrace();
}
writer.format("%s %s ", nameInput.getText(),lastNameInput.getText());
writer.close();
}
这是可行的,但也存在一些问题:
首先,这里的代码是:
if(!file.exists())
file.createNewFile();
它只在路径中不存在的情况下创建新文件
要在文件上写入而不覆盖它,我建议您执行以下操作:
FileWriter fileWriter;
public void write() {
try {
file = new File("c:\\Users\\Me\\Desktop\\text.txt");
if(!file.exists())
file.createNewFile();
// use a FileWriter to take the file to write on
fileWriter = new FileWriter(file, true); // true means that you do not overwrite the file
writer = new Formatter(fileWriter); // than you put your FileWriter in the Formatter
} catch(Exception e) {
e.printStackTrace();
}
writer.format("%s %s ", nameInput.getText(),lastNameInput.getText());
writer.close();
}
希望这是有帮助的!:) 如上所述,我必须通过FileWriter类的构造函数传递文件。这样,我的第一个问题就解决了(我在问题中提到了它们),第二个问题,每当我想添加更多内容时,我都必须重新打开格式化程序
public void write() {
try {
writer = new Formatter(new FileWriter(file,true);
} catch(Exception e) {
e.printStackTrace();
}
writer.format("%s %s ", nameInput.getText(),lastNameInput.getText());
writer.close(); }
文件的创建和初始化应在方法之外一次性完成。不要将
文件
直接传递给格式化程序
构造函数,您可以首先将其包装在新FileWriter(f,true)
中,其中true
启用附加模式并传递该写入程序。但除此之外,您使用Formatter
而不是更常见的PrintStream
或PrintWriter
(两者都提供格式(“格式”,数据…
方法)?@Pshemo是的,我使用Formatter是因为我希望信息采用我想要的格式,然后我可以使用Scanner类读取它们。我知道这里还有很多其他的课程可以更好地使用,但我把它们作为练习的一部分。我对io概念有点陌生,我被认为是将其用于简单的编写和阅读。在internet上的某个地方找到了它
有一个地方可以找到Java运行时如何工作的定义。从2021/06起,确保第16版的,例如for.为true意味着您覆盖了文件
它实际上是相反的。。。不会覆盖任何内容,而是会附加新内容。除此之外,FileWriter FileWriter代码>应该不是一个字段,而是一个局部变量。是的,对不起,我刚才注意到了我的error@Pshemo多亏了你们两位,我的问题解决了。如果您查阅了文档,您应该已经注意到了。(此答案的初始修订版并没有确切指出所提供的代码中与“文件类不删除内容”。(java.io.File
是一个命名错误的路径,这并不奇怪。)