How to create a "new file" .txt in java?

0

My questions are: is this code correct? how do I clear the screen and open the new created file?

menuNovo.setOnAction((ActionEvent e) -> {
            Stage janela = (Stage) areaTexto.getScene().getWindow();
            String nome = JOptionPane.showInputDialog("Digite o nome do arquivo");
            File arquivo = new File(nome + ".txt");
        });

    
asked by anonymous 02.07.2017 / 22:53

1 answer

1

This line is unnecessary:

Stage janela = (Stage) areaTexto.getScene().getWindow();

janela is not being used anywhere within the listener of the event. Remembering that events can be mapped inside the .fxml file itself and referenced in the code with the annotation @FXML .

Do not mix swing and JavaFX. Although there are no problems - for now - it is advisable to keep everything in your square. All components present in the swing can be made with JavaFX without the need to mix them. JOptionPane.showInputDialog() can be replaced with a TextInputDialog - even if it is a bit more verbose, see example code below.

You can also use the package classes java.nio.file.* to manipulate files.

menuNovo.setOnAction((ActionEvent e) -> {

   // Cria o dialog.
   TextInputDialog dialog = new TextInputDialog(null);
   dialog.setTitle("Digite no nome do arquivo");
   dialog.setHeaderText("Digite o nome do arquivo.");;

   // Exibe o dialog e espera pelo valor digitado.
   Optional<String> value = dialog.showAndWait();

   // Se algo for digitado no dialog, cria o arquivo com o nome especificado.
   if (value.isPresent()) {
      try {
         Path file = Paths.get(value.get().concat(".txt"));
         Files.createFile(file);
      } catch (IOException ex) {
         // Tratar exceção no caso de falha na criação do arquivo.
      }
   }
});

If you need to write to the file, it has already been replied here .

    
05.07.2017 / 15:07