如何打开 java 中的文件而不删除其内容?

How can I open a file in java without its contents been removed?

我希望我的程序为用户创建一个文件(只是第一次)并向其中写入一些信息(它不仅是一行,而且以后可以随时调整)。所以我这样做了:

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();
}

可以用,但有一些问题:

  1. 稍后打开文件时,默认情况下,文件 class 会删除其内容。

  2. 当信息写入文件并关闭 Formatter 时,下一次在程序的其他地方再次使用它写入文件时,信息得到更新而不是添加到以前的。如果我不关闭它,它就不会写入。

首先,这里的代码:

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 的构造函数传递文件 class。这样我的第一个问题就解决了(我在问题中提到了它们),对于第二个问题,每当我想添加更多内容时,我都必须重新打开 Formatter。

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();  }

文件的创建和初始化应该在方法之外完成一次。