How to save a file to Javafx or Java?

Asked

Viewed 816 times

1

Code I tried to make, but it doesn’t work:

Javafx FXML Application:

salvar.setOnAction((ActionEvent e) -> {
    Stage window = (Stage) cont.getScene().getWindow();
    try {
        String corpo = cont.getText();
        FileWriter gravarFile = new FileWriter(corpo, false);
        PrintWriter gravar = new PrintWriter(gravarFile + ".txt");
        gravar.write(corpo);
        gravar.close();
    }catch(IOException ex) {
        System.out.println("Conteudo não poderá ser gravado!");
        ex.printStackTrace();

    }
});

What’s wrong with this code above?

  • Hello, better define the error that is happening, if you can put the error/Exception that is being released.

2 answers

1

You don’t need all this effort in Java 8, you can use the method Files#write():

salvar.setOnAction((ActionEvent e) -> {
    Stage window = (Stage) cont.getScene().getWindow();
    try {
        String corpo = cont.getText();

        // path do arquivo (incluindo o nome).
        Path path = Paths.get("C:", "teste", "arquivo.txt"); 
        Files.write(path, corpo.getBytes(), StandardOpenOption.CREATE);

    }catch(IOException ex) {
        System.out.println("Conteudo não poderá ser gravado!");
        ex.printStackTrace();
    }
});

The Imports are all of the package java.nio.file.*.

0

Javafx provides a window to open/save files through the class Filechooser, that can help solve your problem and also improve the usability of your software. Here is the code needed to save a text file:

seuBotao.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        FileChooser chooser = new FileChooser();
        chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text file (*.txt)", "*.txt"));
        File file = chooser.showSaveDialog(primaryStage);

        if(file != null){
            try {
            // Use o mecanismo de escrita que preferir
            FileWriter writer = new FileWriter(file, true);
            writer.write("Escrevendo um arquivo");

            // Não esqueça de fechar o writer
            writer.close();
            } catch (IOException ex){
                // Coloque aqui sua mensagem de exceção
            }       
        }
    }
});

Modify according to your needs. I hope it helps.

Browser other questions tagged

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