BlackLotus
BlackLotus

Reputation: 5

Why is my output file empty in my GUI Java program?

I am making a User Input with GUI. My main goal is to record whatever the user will input and send it to a file 'file.txt' .

But the whenever I open the file, it's empty, even though I already have typed in the textfield. It still returns empty. I am a beginner in Java.

package testpath;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

public class Testpath extends JFrame {

    JLabel label;
    JTextField tf;
    JButton button;

     public Testpath(){
         setLayout(new FlowLayout());

         label= new JLabel("Enter First Name");
         add(label);

         tf=new JTextField(10);
         add(tf);

         button=new JButton("Log In");
         add(button);

         event e=new event();
         button.addActionListener(e);
     }

     public class event implements ActionListener{
         public void actionPerformed(ActionEvent e){
             try{
                 String word=tf.getText();
                 FileWriter stream= new FileWriter("C://Users//Keyboard//Desktop//file.txt");
                 BufferedWriter out=new BufferedWriter(stream);
                 out.write(word);
             }catch (Exception ex){}
         }
     }


    public static void main(String[] args) {
        Testpath gui=new Testpath();
        gui.setLocationRelativeTo(null);
        gui.setVisible(true);
        gui.setSize(400,250);
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  

    }
}

Upvotes: 0

Views: 233

Answers (1)

Pac0
Pac0

Reputation: 23149

You never close your stream, so its contents are never written to disk.

Just call out.close(); after your out.write(); .

You can use out.flush(); if you want the contents written to disk without closing the stream at the same time. (thanks @Ultraviolet)

Upvotes: 1

Related Questions