DateFormat返回null java

时间:2015-08-14 00:22:42

标签: java null

我很困惑。我已经尝试过了,我无法为没有日期的项目分配空值。我究竟做错了什么?

private static String projectDate = null;

public static void main(String[] args) throws Exception {
    DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
    List<Project> projects;
    if (projects == null || projects.size() == 0) {
    } else {
        for (Project project : projects) {
            try {
                projectDate = formatter.format(project.getLastAnalyzedDate().getTime());
            } catch (Exception e) {
                System.err.println("Last Analyzed failed");
            }
            outFile.println("<LastAnalyzed>" + projectDate + "</LastAnalyzed>");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

当projectDate为null时,您无法打印到文件。它将导致NullPointerException。你应该打印检查projectDate是否为null然后打印出“null”字符串。

private static String projectDate = null;
public static void main(String[] args) throws Exception {
    DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
    List<Project> projects;
    if (projects == null || projects.size() == 0) {
    } else {
        for (Project project : projects) {
            try {
                projectDate = formatter.format(project.getLastAnalyzedDate().getTime());
            } catch (Exception e) {
                System.err.println("Last Analyzed failed");
            }
    }
    if(projectDate == null) {
            outFile.println("<LastAnalyzed>" + "null" + "</LastAnalyzed>");
    } else {
            outFile.println("<LastAnalyzed>" + projectDate + "</LastAnalyzed>");
    }
}