【发布时间】:2016-12-17 14:10:01
【问题描述】:
我正在尝试创建一个文本文件并在我的 GUI 应用程序中单击按钮时使用 Java 向其中添加一些详细信息,文本文件的名称必须是当前日期和时间以及文本文件的位置必须是相对的。这是我用来做这个的代码sn-p。
public void actionPerformed(ActionEvent e){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss");
Date date = new Date();
String fileName = dateFormat.format(date) + ".txt";
File file = new File(fileName);
PrintWriter pw;
try{
if(file.createNewFile()){
pw = new PrintWriter(file);
//Write Details To Created Text File Here
JOptionPane.showMessageDialog(null, "The Statistics have successfully been saved to the file: "
+ fileName);
}else{
JOptionPane.showMessageDialog(null, "The save file " + fileName
+ " already exists, please try again in a while.");
}
}catch(IOException exception){
JOptionPane.showMessageDialog(null, exception + ", file name:- " + fileName);
}catch(Exception exception){
JOptionPane.showMessageDialog(null, exception);
}
}
不幸的是,当我运行上述代码时,出现以下错误:
我找不到问题,请告诉我我做错了什么。
【问题讨论】:
-
文件名中不能有斜杠 (
/) -
我尝试使用
new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");,但仍然遇到同样的错误。 -
@lordvlad 我现在试过了,它奏效了。
yyyy-MM-dd HH-mm-ss格式有效。感谢您的帮助。 -
认真的吗?我看不出错误消息怎么能比这更清楚?它几乎从字面上告诉你,你不能这样命名你的文件!
-
@Fildor 是的,我意识到现在答案很简单,但我仍然是编程和堆栈溢出的新手。请告诉我你是否认为这个问题应该被删除,因为它在未来对其他人没有用处。
标签: java file-writing