Reputation: 304
I'm making a program in which user enter values in text fields then it generates a directory and text file. But issue is when I run the program it generates directory also when the program catch an exception then it's create a text file. I only want that happen on user enter values. Then it makes directory and text file.
Second: When text file is generated then on again program runs text file is replaced with new one. Old one is replaced. I want to make new text file on again program run like open1.txt & open2.txt
Code:
public class V extends JFrame{
private JTextField t1;
private JTextField t2;
private JButton b1;
public V(){
File file1 = new File("C:\\Users\\hamel\\Desktop\\z");
file1.mkdirs();
File file2 = new File("C:\\Users\\hamel\\Desktop\\z\\open.txt");
getContentPane().setLayout(null);
t1=new JTextField();
t1.setBounds(30,26,47,28);
getContentPane().add(t1);
t2=new JTextField();
t2.setBounds(103,26,47,28);
getContentPane().add(t2);
b1=new JButton("Click");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String w = t1.getText();
String x = t2.getText();
int i,j ,k;
try{
PrintWriter pw = new PrintWriter(file2);
i = Integer.parseInt(w);
k = Integer.parseInt(x);
pw.println("You Enter in Text Field 1:"+i);
pw.println("You Enter in Text Field 2:"+k);
pw.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Error");
}
}
});
b1.setBounds(235,26,87,28);
getContentPane().add(b1);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Main:
public class Open_2 {
public static void main(String[] args) {
V next = new V();
}
}
Upvotes: 1
Views: 52
Reputation: 14448
For your first problem:
You are creating the directory even before your GUI is layedout. Hence it is always created. If you don't want the directory and file to be created if there is an exception move your file1.mkdirs();
to the action listener and modify your try block to something like this.
try {
i = Integer.parseInt(w);
k = Integer.parseInt(x);
file1.mkdirs();
File file2 = File.createTempFile("open", ".txt", file1);
PrintWriter pw = new PrintWriter(file2);
pw.println("You Enter in Text Field 1:"+i);
pw.println("You Enter in Text Field 2:"+k);
pw.close();
}
For your second problem:
If you want a new file to be created everytime starting with the name open
but not necessarily open1
and open2
and so on, you can use
File file2 = File.createTempFile("open", ".txt", file1)
after your file1.mkdirs()
command.
But remember, createTempFile command will generate a random name starting with open
and ending with .txt
but not necessarily open1.txt
, open2.txt
and so on.
Upvotes: 1