【问题标题】:Generate a txt file, from another given, with the dates ordered, and those between two other dates given从另一个给定的日期生成一个 txt 文件,其中包含已排序的日期,以及给定的其他两个日期之间的日期
【发布时间】:2019-04-20 13:09:49
【问题描述】:

我正在尝试创建一个方法,给定一个输入 txt 文件和两个 LocalDate 日期,返回另一个文件,其中包含两个给定日期之间的日期,并进行排序。 我已经知道如何读取文件,创建另一个文件,并在新文件中引入排序的日期。但我不知道如何确定两者之间的日期。我正在尝试使用 while 循环来做到这一点。 如果你有什么想法,能照亮我的路真是太棒了。我给你看已经有的代码,谢谢。

private static File fileGenerator(String f_input, LocalDate Date1, LocalDate date2) throws FileNotFoundException, IOException {
 FileReader fr=new FileReader (f_input);
 BufferedReader br=new BufferedReader(fr);
 File f_output=new File("C:/Users/Ivan/Documents/output_file.txt");
 FileWriter fw = new FileWriter(f_ouput);
 BufferedWriter bw = new BufferedWriter(fw);

 //Here, i create a list where I will drop every line from f_input
 LinkedList<String> list = new LinkedList<String>();
 String line=null;
 while((line=br.readLine())!=null) {
    list.add(line);
 {

 //Now, I sort the list
 Collections.sort(list);

 Iterator iter = list.iterator();
 String c;
 while(iter.hasNext()){
    c=(String) iter.next();
    bw.append(c);
    bw.newLine();
    bw.flush();
 {

 br.close();
 fr.close();
 fw.close();

 return f_ouput;

【问题讨论】:

  • 但我不知道如何缩小给定日期之间的范围。 -- 抱歉,这是什么意思?
  • 对不起我的糟糕表达。这意味着在给定两者之间的日期。
  • 您的意思是用户将输入 2 个日期,而您只需将它们之间的日期写入文件?
  • 没错。我只需要在新返回的文件中包含介于两者之间的日期,对它们进行排序。
  • 日期的格式是什么?可以分享几行您正在阅读的输入文件吗?

标签: java file loops while-loop localdate


【解决方案1】:

谓词是表示“是否允许此行”的函数。要允许一行,它应该返回 true。

这个谓词函数可以传递给一个集合来过滤它。

例如:

public static List<Employee> filterEmployees (List<Employee> employees,
                                            Predicate<Employee> predicate)
{
    return employees.stream()
                .filter( predicate )
                .collect(Collectors.<Employee>toList());
}

上面的例子是 Java 8 以后的版本。

以下是本文中更详尽的列表: https://www.baeldung.com/java-collection-filtering

我也喜欢上篇文章中提到的Google Guava库的Collections2.filter方法。

Collection<MyClass> result = Collections2.filter(baseCollection, predicate);

当然,仍然必须编写谓词来解析文件中的日期并将它们与输入日期范围进行比较。

【讨论】:

  • Erm.. 这如何回答这个问题?
  • 你,Teddy,试图向我解释这一点的方式令人困惑。至少对我来说,我只是一个试图理解的工科学生哈哈哈。顺便谢谢你。
  • @NicholasK 我认为 OP 知道 Collections.sort 方法并且正在寻找 Collections API 中的过滤方法:)
【解决方案2】:

您需要执行以下操作:(如果您愿意,可以使用伪代码)

  1. 使用以下代码转换文件中的每个字符串:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    // for example 
    LocalDate test = LocalDate.parse(string_frm_file, formatter);
    
  2. 现在您需要比较 LocalDate(此处为测试)以查看它是否在传递给您的方法的范围内。如果它确实将其添加到要写入文件的列表中,则忽略它。

    if (date1.isBefore(test) && date2.isAfter(test)) {
        list.add(test);
    }
    

【讨论】:

  • 我将这段代码改编为我的代码,但告诉我,例如,无法在索引 4 处解析文本“1999,04,22”。
  • 我只是格式化为“yyyy/MM/dd”,结果发生了
  • 好的现在正在“格式化”,但它告诉我无法从 TemporalAccesor 获取 LocalDate:[Year=1999, DayOfMonth=22, MinuteOfHour=4].... MINUTE OF HOUR??跨度>
  • 好的,现在正在工作。一切顺利。非常感谢您,先生,非常感谢您的宝贵时间。
猜你喜欢
  • 2010-10-07
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 2015-07-01
  • 2020-06-30
  • 1970-01-01
相关资源
最近更新 更多