【问题标题】:Why is my ArrayList not being saved to my file?为什么我的 ArrayList 没有保存到我的文件中?
【发布时间】:2013-04-19 00:01:03
【问题描述】:

为什么 ArrayList 没有写入“MyCalendar.txt”?即使我使用 out.write() 它仍然返回 false 但不写入文件。

import java.util.*;
import java.io.*;

public static Boolean addAppointment(ArrayList<String> calendar, 
                     String specifiedDay,
                         String specifiedTime) {

PrintWriter out = new PrintWriter("myCalendar.txt"); //declare calendar file    


    for (int i = 0; i<calendar.size(); i++) {
        String index = calendar.get(i);
        if (index.equals(specifiedDay + "" + specifiedTime))
        { 
         out.println(specifiedDay + "" + specifiedTime);
         return false; 
        }
    }
    return true;
}

【问题讨论】:

  • 你应该有 PrintWriter out = new PrintWriter("myCalendar.txt");try/catch 包围。

标签: java arraylist printwriter


【解决方案1】:

以下 2 对刷新数据到文件和关闭流很重要

out.flush();
out.close();

问候,

【讨论】:

  • 关闭流会自动刷新流。
  • 谢谢!我们从来没有被教导在课堂上刷新数据,但这显然是我需要做的。另外,我使用 out.write(specifiedDay + specifiedTime + '\n') 将其保存在文件中。
  • 如果你使用 out.println 那么你不需要\n。因为 println 表示打印该行并终止。但是如果你使用 out.write() 那么你需要使用 \n 来写行并终止。所以接下来的写作将从新的一行开始。问候,
【解决方案2】:

你忘了关闭它:

out.close()

【讨论】:

  • 关闭前您可能还需要out.flush()
  • @Joe,close 在关闭流之前自动将内容刷新到文件。所以冲洗是一种可选的。
【解决方案3】:

所以,这里有几件事。

如果您使用的是 Java 7,则应考虑使用 try-with-resources。这绝对可以确保您的PrintWriter 在您完成后关闭。

try (PrintWriter out = new PrintWriter("somefile.txt")) {
    // code
} catch (FileNotFoundException e) {
    System.out.println("Bang!");
}

接下来,有几种情况会导致部分或根本无法写入文件:

  • calendar.size() == 0
  • index.equals(specifiedDay + "" + specifiedTime)

如果满足第一个条件,则不写入任何内容,并且该方法愉快地返回true。可能不是你所期望的。

如果满足第二个条件,则编写 first 元素,并提前返回。将它放在循环条件中可能是一个更好的主意,并在循环完成后返回返回值。

int i = 0;
boolean good = true;
while(good && i < calendar.size()) {
    // critical actions
    String index = calendar.get(i);
    if(index.equals(specifiedDay + "" + specifiedTime)) {
        good = false;
    }
}
// other code
return good;

如果该条件从不满足,则不会向文件写入任何内容。

【讨论】:

    【解决方案4】:

    PrintWriter 的默认行为是不自动刷新缓冲区。有关详细信息,请参阅PrintWriter Documentation

    或者,您可能遇到数据问题:

    String index = calendar.get(i);
    if (index.equals(specifiedDay + "" + specifiedTime))
    

    如果不满足此条件,您将不会打印任何内容。你确定这个条件是真的吗?

    【讨论】:

      猜你喜欢
      • 2011-11-14
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多