Java:文件目录和替换问题
问题描述:
我正在制作一个程序,用户在文本字段中输入值,然后生成一个目录和文本文件。但问题是当我运行它生成的程序目录时,当程序发现异常时,它也会创建一个文本文件。我只希望发生在用户输入值上。然后它使目录和文本文件。Java:文件目录和替换问题
第二个: 当生成文本文件,然后再次运行程序运行文本文件被替换为新的。旧的被替换。我想使新的文本文件上再次运行程序一样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块修改为如下所示。
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
等,你可以使用
在您的file1.mkdirs()
命令后输入File file2 = File.createTempFile("open", ".txt", file1)
。
但要记住,createTempFile命令将生成一个随机的名称以open
与.txt
结束,但不一定open1.txt
,open2.txt
等。
第一个问题是解决。你可以做一个第二个问题的代码。 – hamel123
答案已经给第二个问题的选项也...你不满意吗? – Codebender
尝试{ \t \t \t PrintWriter pw = new PrintWriter(file2); \t \t \t \t i = Integer.parseInt(w); \t \t \t \t \t \t \t K =的Integer.parseInt(X); \t \t \t file1.mkdirs();当单击按钮时它会发生异常错误 – hamel123