您好我正在尝试将日期和时间添加到JAVA中的文件名。我可以在文件中打印日期和时间,这也是我想要完成的,但是当我将toString放在FileWriter中时,我得到一个空指针。
package com.mkyong;
import java.util.*;
import java.io.*;
import java.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Simplex {
private static PrintWriter outFile;
//Main Method
public static void main(String[] args) throws IOException {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
outFile.println(date.toString());
outFile.println();
//creates the new file to be saved
outFile = new PrintWriter(new FileWriter("simplex" + (date.toString()) + ".txt"));
答案 0 :(得分:6)
如果使用java 8
DateTimeFormatter timeStampPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
System.out.println(timeStampPattern.format(java.time.LocalDateTime.now()));
答案 1 :(得分:5)
第一次使用outFile之前应该出现outFile = new PrintWriter(..)
行。
基本上你在初始化之前使用outFile。
答案 2 :(得分:2)
我建议您在文件名中使用YYYY-MM-dd_hh-mm-ss
格式设置模式,以便您以更方便的方式对文件进行排序。看一下SimpleDateFormat
课程。
...
Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss");
outFile = new PrintWriter(new FileWriter("simplex_" + formatter.format(date) + ".txt"))
...
答案 3 :(得分:0)
// display time and date using toString()
outFile.println(date.toString());
使用代码,您可以在初始化之前使用outFile
。
答案 4 :(得分:0)
只需将其保存在变量中即可。你应该使用新的Date(长)构造函数,顺便说一句。
public class Simplex {
private static PrintWriter outFile;
//Main Method
public static void main(String[] args) throws IOException {
// Instantiate a Date object
Date date = new Date(System.currentTimeMillis());
String dateString = date.toString();
outFile = new PrintWriter(new FileWriter("simplex" + dateString + ".txt"));
outFile.println(dateString);
outFile.println();
//creates the new file to be saved
答案 5 :(得分:0)
问题是outFile被声明为静态,但在你使用它之前从未初始化。
在实际使用之前,首先需要先初始化/实例化outFile:
private static PrintWriter outFile;
//Main Method
public static void main(String[] args) throws IOException {
// Instantiate a Date object
Date date = new Date();
//creates the new file to be saved
outFile = new PrintWriter(new FileWriter("simplex" + (date.toString()) + .txt"));
// display time and date using toString()
outFile.println(date.toString());
outFile.println();
虽然我不完全确定为什么你甚至将outFile创建为静态对象,而不仅仅是局部变量。
答案 6 :(得分:0)
可以使用下面提到的代码段
String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
logFileName = "loggerFile_" + logFileName;