微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在不删除内容的情况下在java中打开文件?

如何解决如何在不删除内容的情况下在java中打开文件?

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

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. 文件稍后打开时,认情况下,File 类会删除内容

  2. 当信息被写入文件并且格式化程序被关闭时,下次当我再次使用它来写入文件时,程序中的其他地方,信息会被更新而不是添加到以前的信息中。如果我不关闭它,它就不会写入。

解决方法

首先,这里的代码:

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 ",lastNameInput.getText());

writer.close();  }

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。