How to save a file in JavaFX or Java?

1

Code I tried to do but it does not 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?

    
asked by anonymous 30.06.2017 / 22:10

2 answers

1

You do not need all this effort in Java 8, you can use the 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();
    }
});

imports are all in the package java.nio.file.* .

    
30.06.2017 / 22:49
0

JavaFX provides a window for opening / saving files through the FileChooser , which 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. Hope it helps.

    
01.07.2017 / 16:42