【问题标题】:How do I code the function of the Save button in Java?如何在 Java 中编写保存按钮的功能?
【发布时间】:2014-06-09 03:53:51
【问题描述】:

我有一个现有的文本文件并在其中编辑了一些内容。我想将一行文本保存到同一个文件中。目前,我的保存按钮将为我刚刚编辑的文本文件创建一个新文件。我想要的是我的保存按钮只会覆盖现有文件。我需要在上面写什么代码?

这是我当前的代码:

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
    JFileChooser fc = new JFileChooser();

    int choice = fc.showSaveDialog(null);
    if (choice == JFileChooser.APPROVE_OPTION) {
        String filename = fc.getSelectedFile().getAbsolutePath();
        writeToFile(filename);
    }
}                                    

这是我的 writeToFile 代码:

       private void writeToFile(String filename) {
       Person p = getPersonFromDisplay();
       PersonFileMgr.save(filename, p);
   }

【问题讨论】:

  • 你现在有什么代码?
  • writeToFile 方法在哪里?
  • 抱歉拖了太久。

标签: java file button text save


【解决方案1】:

在不创建全新文件的情况下覆盖文件。使用FileWriterBufferedWriter

示例:

在您的 writeToFile 方法中

try{
    FileWriter fstream = new FileWriter("out.txt",true);
    BufferedWriter out = new BufferedWriter(fstream);
    out.write("Hi\n");
    out.close();
    }catch (Exception e){
      System.err.println("Error: " + e.getMessage());
    }
  }

【讨论】:

    【解决方案2】:

    你可以这样做:

    InputStream ios = null;
    OutputStream out = null;
    try {
        ios = new FileInputStream(file);
        byte[] buffer = new byte[SIZE];
        int read;
        out = new FileOutputStream(file);
        while ((read = ios.read(buffer)) != -1) {
            out.write(buffer, 0, read);
            out.flush();
        }
    } catch (IOException e) {
        log.error("Saving failed", e);
    } finally {
        if (ios != null) {
            ios.close();
        }
        if (out != null) {
            out.close();
        }
    }
    

    请注意,在我们当前的代码中,您不需要多个变量作为选项和文件名,您可以内联它们。没有理由拥有它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多