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

Asked

Viewed 1,113 times

0

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

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

como faço para limpe a tela e abre o novo arquivo criado?

1 answer

1

This line is unnecessary:

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

janela is not being used anywhere within the Listener 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 the time being — It is recommended to keep each thing in its square. All components present in the swing, can be made with Javafx without the need to mix them. JOptionPane.showInputDialog() may be replaced by a TextInputDialog - even if it is a little 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 in the file, has been answered here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.