this question may have been asked before but didn’t find any clue for my problem here,
here is my problem : I have a file that is like this :
abc fg Sat Jan 08 19:06:21 IST 2022 4 4.0
here is my code that reads from the file :
BufferedReader read4 = new BufferedReader(new FileReader("shortDelvsFile.txt")); while ((s = read4.readLine()) != null) { token = new StringTokenizer(s); double str1 = Double.parseDouble(token.nextToken()); Integer str2 = Integer.parseInt(token.nextToken()); while (token.hasMoreTokens()) { System.out.println(convert(token.nextToken())); } ShortDeliveries d = new ShortDeliveries(token.nextToken(), token.nextToken(), convert(token.nextToken()), str2, str1); shortDelvss.add(d); } System.out.println("the short deliveries are : " + shortDelvss); read4.close(); // this function is to convert the string to date public static Date convert(String s) throws ParseException { Date date = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH).parse(s); System.out.println(date); return date; }
now i want each “token.nextToken();“` inside the ShortDeliveries to be like this:
token.nextToken() = fg convert(token.nextToken()) = Sat Jan 08 19:06:21 IST 2022 str1 = 4 str2 = 4.0;``` the problem is that in convert(token.nextToken()) it doesn't take the whole date because tokenizer reads until the first space how can i fix that?
Advertisement
Answer
In case you know the date will always start with the day of week (e.g. Sat, Sun…), you can create a method to check if the current token is a known day. In case this is a week day, collect the following 6 tokens (or whatever tokens count you need to form a valid date) and send them together as String to your convert method.
if (isDayOfWeek(token)) { List<String> dateTokens = getNextTokens(token, 6); String dateString = String.join(" ", dateTokens); Date date = convert(dateString); } private boolean isDayOfWeek(String dayString) { Locale locale = Locale.getDefault(); return Arrays.stream(DayOfWeek.values()) .map(day -> day.getDisplayName(TextStyle.SHORT, locale)) .anyMatch(dayString::equals); } private List<String> getNextTokens(StringTokenizer token, int tokenCount) { return IntStream.rangeClosed(1, tokenCount) .mapToObj(i ->token.nextToken()) .collect(Collectors.toList()); }