Search code examples
javagetwriter

Creating a .txt File named with a .get method


I am trying to build up a form. At the end of the form I'd like the save button to create a TXT file named after the surname the person entered in the form. I only succeed in creating a txt file with a defined name (that I choose) or a file with no extension that got the surname info. Here is the code, thank you all for the attention:

    Button btnSalva = new Button(shell, SWT.NONE);
    btnSalva.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            BufferedWriter writer = null;
            try {
                writer = new BufferedWriter(new FileWriter(text_1.getText()));

                writer.write("Nome" + text.getText() + "Cognome" + text_1.getText() + "età" + text_2.getText());

            } catch (IOException e1) {
            } finally {
                try {
                    if (writer != null)
                        writer.close();
                } catch (IOException e1) {

                }
            }

        }

    });
    btnSalva.setBounds(10, 799, 75, 25);
    btnSalva.setText("SALVA");

Solution

  • Well if surname is your text_1.getText(), and you want a TXT extension, just change your line :

    writer = new BufferedWriter(new FileWriter(text_1.getText()));
    

    into

    writer = new BufferedWriter( new FileWriter( text_1.getText() + "TXT" ));