【问题标题】:How can I open a file in java without its contents been removed?java - 如何在不删除内容的情况下在java中打开文件?
【发布时间】:2021-08-23 17:03:08
【问题描述】:

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

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. 当信息被写入文件并且 Formatter 关闭时,下次在程序中的其他地方我再次使用它来写入文件时,信息会更新并且不会添加到以前的信息中。如果我不关闭它,它就不会写。

【问题讨论】:

  • 而不是将file 直接传递给Formatter 构造函数,您可以首先将其包装在new FileWriter(f,true) 中,其中true 启用附加模式并传递该编写器。但除此之外,您使用Formatter 而不是更常见的PrintStreamPrintWriter(两者都提供format("format", data...) 方法)是否有某些特定原因?
  • @Pshemo 是的,我正在使用格式化程序,因为我希望信息采用我想要的格式,然后我可以使用 Scanner 类读取它们。我知道还有很多其他的课程可以在这里更好地使用,但我将这些课程用作练习的一部分。我对 io 概念有点陌生,我被认为可以将这些用于简单的写作和阅读。
  • found this somewhere on the internet一个地方你应该寻找Java运行时应该如何工作的定义。从 2021/06 开始,将其设为 Java Standard Edition Documentation 的第 16 版,例如 nio

标签: java file io java-io formatter


【解决方案1】:

首先,这里的代码:

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

希望这对您有所帮助! :)

【讨论】:

  • true means that you overwrite the file 它实际上是相反的......不会覆盖任何内容,而是会附加新内容。除此之外,FileWriter fileWriter; 不应该是一个字段,而是一个局部变量。
  • @Pshemo 谢谢你们,我的问题解决了。
【解决方案2】:

如上所述,我必须通过 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();  }

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
相关资源
最近更新 更多