我想創建一個文本文件並在Java應用程序中單擊按鈕時使用Java添加一些細節,文本的名稱文件必須是當前日期和時間,文本文件的位置必須是相對的。這是我用來做到這一點的代碼片段。用當前日期和時間創建一個文本文件作爲Java中的文件名
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);
}
}
不幸的是,當我運行上面的代碼中,我得到以下錯誤:
我不能發現問題,請告訴我,我做錯了。
你不能在你的文件名中使用斜槓('/') – lordvlad
我試過'新的SimpleDateFormat(「yyyy-MM-dd_HH-mm-ss」);'但我仍然收到同樣的錯誤。 –
@lordvlad我現在試過了,它工作。格式'yyyy-MM-dd HH-mm-ss'工作。謝謝您的幫助。 –