【问题标题】:How to read file and add to array based on specific input range如何根据特定输入范围读取文件并添加到数组
【发布时间】:2023-03-12 09:44:01
【问题描述】:

这是我的文本文件的内容:

温度:格林威治标准时间 2014 年 12 月 12 日星期五 1:35:48,读数:22 摄氏度-
温度:2014 年 12 月 12 日星期五 1:36:48 GMT,读数:25 摄氏度-
温度:2014 年 12 月 13 日星期五 2:12:48 GMT,读数:25 摄氏度-
温度:2014 年 12 月 14 日星期五 2:12:48 GMT,读数:25 摄氏度-
温度:2014 年 12 月 14 日星期五 3:12:48 GMT,读数:27 摄氏度-
温度:2014 年 12 月 15 日星期五 3:12:48 GMT,读数:99 摄氏度-
温度:2014 年 12 月 15 日星期五 4:12:48 GMT,读数:69 摄氏度-
温度:2014 年 12 月 15 日星期五 5:12:48 GMT,读数:68 摄氏度-

例如,我怎样才能只添加特定范围之间的读数并将其添加到我的数组中?

例如,如果我输入 13 和最多 15 个日期,则数组的读数应该在 12 月 12 日到 12 月 14 日之间以及 2 到 3 小时之间。没有任何结果...

public static String readwrite2(String namefile) throws IOException {
    StringBuilder builder = new StringBuilder();
    List<String> words = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(new FileReader(namefile));

    Scanner scanner = new Scanner(System.in);

    System.out.println("specify date from: ");
    String a = scanner.nextLine();
    System.out.println("specify from hour:  ");
    String b = scanner.nextLine();
    System.out.println("specify up to which date: ");
    String c = scanner.nextLine();
    System.out.println("specify up to which hour: ");
    String d = scanner.nextLine();
    System.out.println("Your input is " + a + b);
    String line;

    String currentdate=a, currenthour=b;
        String nextdate = String.valueOf(Integer.parseInt(currentdate) +1);
        String nexthour = String.valueOf(Integer.parseInt(currenthour) +1);
    while ((line = reader.readLine()) != null) {
        if (line.contains("Dec "+currentdate+" "+currenthour)){
            words.add(line);
        }
    currentdate=nextdate;
    currenthour=nexthour;
    }
}

for (String s : words)
    builder.append(s);
    reader.close();
    return builder.toString();
}

List<String> myList = new ArrayList<String>(Arrays.asList(builder.split("-")));
for(int i = 0; i < myList.size(); i++) {   
    System.out.println(myList.get(i));
}  

所以结果应该给出以下读数:

Temperature : Fri Dec 13 2:12:48 GMT 2014, Reading: 25 Celcius-  
Temperature : Fri Dec 14 2:12:48 GMT 2014, Reading: 25 Celcius-  
Temperature : Fri Dec 14 3:12:48 GMT 2014, Reading: 27 Celcius-  
Temperature : Fri Dec 15 3:12:48 GMT 2014, Reading: 99 Celcius-

非常感谢任何帮助,谢谢。

【问题讨论】:

    标签: java arraylist bufferedreader


    【解决方案1】:

    你可以用','分割(String.split(","))每一行,你会得到一个字符串数组,例如: Temperature : Fri Dec 12 1:35:48 GMT 2014Reading: 22 Celcius-

    对该数组的第一个元素进行第二次拆分将为您提供另一个数组,其第二个元素是日期时间格式: 格林威治标准时间 2014 年 12 月 12 日星期五 1:35:48

    在此处设置过滤逻辑并继续。

    【讨论】:

    • 这并不能真正回答我的问题,但我得到的结果与我的问题结果相似,因为我使用“-”来分割我的结果。主要问题是我想要基于输入的文本文件的特定读数。感谢您的反馈
    • 你还需要过滤日期,EEE MMM yy HH:mm:ss z yyyy
    猜你喜欢
    • 2022-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多