简体   繁体   中英

Get a time value from a text file in Java

Is there any way to extract a time value from a text file. The format of the text file is

Jack Johnson Sunday 1100 - 1500,

I cannot find a way to extract these 2 times from a text file by themselves. This code below is what I have so far and it works for strings but I cannot find a way to get it to extract the time ranges within the text file

Boolean isAvail = false;
Date day = new Date();

SimpleDateFormat simpleDateformat = new SimpleDateFormat("EEEE");
String token1 = "";

Scanner inFile1 = new Scanner(new File("F:\\Example\\text.txt")).useDelimiter(",\\s*");

List<String> availability = new ArrayList<String>();

while (inFile1.hasNext()) 
    {
        token1 = inFile1.next();
        availability.add(token1);
    }
    inFile1.close();


    String[] availabilityArray = availability.toArray(new String[0]);

    String searchArray = simpleDateformat.format(day);
    for (String curVal : availabilityArray)
    {
        if (curVal.contains(searchArray))
        {
        System.out.println(curVal);
        }
    }

If you have fixed format file as you showed then you do not need to complicate it with DateFormat, scanner delimiter etc.

just process file line by line, split each line by space and have each value in its own place in the array, as example:

   Scanner inFile1 = new Scanner(new File("F:\\Example\\text.txt"));

    while (inFile1.hasNext()) {
        token1 = inFile1.nextLine();
        availability.add(token1);
    }
    inFile1.close();

    System.out.println(availability.get(0));
    String[] availabilityArray = availability.toArray(new String[0]);

    for (String line : availabilityArray) {
        System.out.println("line: " + line);
        System.out.println("----");
        String[] lineTokens = line.split("\\s");
        System.out.println("name: " + lineTokens[0] + " " + lineTokens[1]);
        System.out.println("day: " + lineTokens[2]);
        System.out.println("start: " + lineTokens[3]);
        System.out.println("end: " + lineTokens[5]);
        System.out.println("----");
    }

BTW there are tons of possibilities, more complex, more simple, more elegant, etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM