我正在制作一个程序,用户在文本字段中输入值,然后生成一个目录和文本文件。但问题是,当我运行程序时,它也会生成目录,当程序捕获异常时,它会创建一个文本文件。我只希望这种情况发生在用户输入值时。然后它创建目录和文本文件。
第二: 生成文本文件后,程序再次运行,文本文件将被新文件替换。旧的被替换了。我想在程序上再次运行新的文本文件,如 open1.txt 和 open2.txt
代码:
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);
}
}
主要:
public class Open_2 {
public static void main(String[] args) {
V next = new V();
}
}
最佳答案
对于您的第一个问题:
您甚至在 GUI 布局之前就创建了该目录。因此它总是被创建。如果您不希望在出现异常时创建目录和文件,请将 file1.mkdirs();
移动到操作监听器并将 try block 修改为类似这样的内容。
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();
}
对于你的第二个问题:
如果您希望每次都以名称 open
开头创建一个新文件,但不一定是 open1
和 open2
等,您可以使用
File file2 = File.createTempFile("open", ".txt", file1)
在 file1.mkdirs()
命令之后。
但请记住,createTempFile 命令将生成一个以 open
开头并以 .txt
结尾的随机名称,但不一定是 open1.txt
,open2.txt
等等。
关于Java:文件目录和替换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30863716/