java - append 到文件时如何关闭 JavaFX FileChooser 的覆盖警告?

标签 java io append javafx-8 filechooser

我需要创建一个数据输入 JavaFx 类,它以 append 模式输出到文件。在下面的简化可运行示例(已删除导入)中,我可以创建一个文件,放入初始数据,然后毫无问题地 append 到该文件。但是,如果我关闭该程序并稍后再次运行它,FileChooser 将帮助查找该文件,但会发出警告: “确认另存为__ TryFile.txt 已存在。 __ 您想更换它吗?”。

如果我选择确认,新数据将按预期 append ,并且文件不会被替换。 我如何关闭该警告?我在 Windows 7 上使用 Java 8_20。

注意:我已根据以下建议更正了代码。请参阅AppendToFile()。

public class TryAppend extends Application
{
  static File file;

  static void initiatefile( String setupInfo )
  {
    FileChooser choose = new FileChooser();
    choose.getExtensionFilters().add(
            new FileChooser.ExtensionFilter( "Text doc(*.txt)", "*.txt" ) );
    choose.setInitialFileName( "*.txt" );
    choose.setInitialDirectory( new File(System.getProperty("user.home") ) );
    file = choose.showSaveDialog( null );
    if ( file != null )
    {
        if ( file.getName().endsWith( ".txt" ) )
        {
           try( PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( file )))) 
           {
               out.println( setupInfo );
           }catch (IOException e) {
               System.err.println(e);
           }
        }
    }
  }

  static void appendToFile( String appendString )
  {
    if (file == null)
    {
        FileChooser choose = new FileChooser();
        choose.getExtensionFilters().add(
                new FileChooser.ExtensionFilter( "Text doc(*.txt)", "*.txt" ) );
        choose.setInitialDirectory( new File(System.getProperty("user.home") ) );
        file = choose.showOpenDialog( null ); //Now corrected. Previously 
                                              //was: choose.showSaveDialog( null );                    
    }

    if ( file != null )
    {   

        try( PrintWriter out = new PrintWriter( new BufferedWriter( new FileWriter( file, true )))) 
        {
            out.println( appendString );
        }catch (IOException e) {
            System.err.println(e);
        }
    }
  }

  @Override
  public void start(Stage primaryStage) 
  { 
     primaryStage.setTitle( "Try Append to File" ); 
     Group root = new Group(); 
     Scene scene = new Scene( root, 300, 200 ); 
     Button initBtn = new Button(); 
     initBtn.setLayoutX( 100 ); 
     initBtn.setLayoutY( 40 ); 
     initBtn.setText( "Initiate File" ); 
     initBtn.setOnAction( new EventHandler<ActionEvent>() 
     { 
        public void handle(ActionEvent event) 
        { 
            initiatefile( "Initial data" ); 
        } 
     } ); 
     Button appendBtn = new Button(); 
     appendBtn.setLayoutX( 90 ); 
     appendBtn.setLayoutY( 100 ); 
     appendBtn.setText( "Append to File" ); 
     appendBtn.setOnAction( new EventHandler<ActionEvent>() 
     { 
        public void handle(ActionEvent event) 
        { 
            appendToFile( "Appended data" );
        } 
     } ); 
     root.getChildren().add( initBtn ); 
     root.getChildren().add( appendBtn ); 
     primaryStage.setScene( scene ); 
     primaryStage.show(); 
  }
  public static void main(String[] args) 
  {
    launch(args);
  }
}

最佳答案

另存为对话框无法执行此操作,因为提示覆盖在 GTK source file 中被硬编码为 TRUE :

gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER (chooser), TRUE);

JDK-8299969已记录此问题,需要先解决该问题,然后才能忽略覆盖提示。

使用打开对话框是一种解决方法,尽管它有缺点。

对于KeenWrite ,我选择使用一个热键,通过重复之前的导出操作来完全绕过另存为对话框。这可以通过创建一个能够重新运行 javafx.concurrent.Taskjavafx.concurrent.Service 来完成,例如:

final var service = new Service<Path>() {
  @Override
  protected Task<Path> createTask() {
    final var task = new Task<Path>() {
      @Override
      protected Path call() throws Exception {
        // Do the work that Save As would do.
      }
    };

    // Handle the success functionality.
    task.setOnSucceeded( this::successs );

    // Handle the failure functionality.
    task.setOnFailed( this::failure );

    return task;
  }
};

这样,如果另存为是用户可能经常使用的功能,则可以将其替换为不提示任何对话框的“静默”版本。第一次除外,它创建将重新运行以供后续“静默”执行的初始操作。

关于java - append 到文件时如何关闭 JavaFX FileChooser 的覆盖警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25045636/

相关文章:

java - Spring Controller 中搜索的方法不起作用

Jquery .append 语法

node.js - Gridfs 对 Node native 写入性能的影响

java - 如何在java中使用正则表达式分割字符串

java - 将鼠标悬停在另一个单元格上时如何删除 JTable 单元格 bgColor?

java - Spring 安全 - 自定义 ExceptionTranslationFilter

C++ 打印在 main 中声明的数组的内容

scala - 猫效应 : How to transform `List[IO]` to `IO[List]`

haskell - 在 Haskell 中,我想读取一个文件,然后写入它。我需要严格注释吗?

pandas - 如何使用 Pandas 将新的数据帧行 append 到 csv?