Create .ics Calendar File in Java | Generate ICS File using Spring Boot REST API | iCal4j

  • Last updated Apr 25, 2024

In this example, we will show you how to create an ICS file in Java and Spring Boot using iCal4j library.

iCal4j is a Java library that helps to create, read, write, and manipulate iCalendar files. An iCalendar file has .ics extension. An ICS file contains plain text with calendar event details such as starting and ending time of events, event description, meetings, and appointments. The iCalendar standard provides a common data format for storing information about calendar specific events data. The iCalendar standard supports many calendaring tools, such as Outlook, Lotus Notes, Apple's iCal, and Google Calendar.

  1. The first step is to install iCal4j library to your Java or Spring Boot project.
  2. For Maven:

    <dependency>
        <groupId>org.mnode.ical4j</groupId>
        <artifactId>ical4j</artifactId>
        <version>4.0.0-beta8</version>
    </dependency>
    

    For Gradle:

    implementation group: 'org.mnode.ical4j', name: 'ical4j', version: '4.0.0-beta8'


  3. Create ical4j.properties file at /src/main/resources/ical4j.properties location of your project and add the following:

  4. net.fortuna.ical4j.timezone.cache.impl=net.fortuna.ical4j.util.MapTimeZoneCache

  5. The next step demonstrates two examples of creating .ics files: the first example in Java and the second example in Spring Boot.

  6. Here's a Java code snippet for creating an .ics file:


    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.time.Instant;
    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.util.GregorianCalendar;
    import java.util.TimeZone;
    import net.fortuna.ical4j.data.CalendarOutputter;
    import net.fortuna.ical4j.model.Calendar;
    import net.fortuna.ical4j.model.component.VEvent;
    import net.fortuna.ical4j.model.property.Attendee;
    import net.fortuna.ical4j.model.property.Location;
    import net.fortuna.ical4j.model.property.Organizer;
    import net.fortuna.ical4j.model.property.ProdId;
    import net.fortuna.ical4j.model.property.Uid;
    import net.fortuna.ical4j.util.RandomUidGenerator;
    import net.fortuna.ical4j.util.UidGenerator;
    import net.fortuna.ical4j.validate.ValidationException;
    
    public class Example {
    
       public static void main(String[] args) {
    
          /* Event start and end time in milliseconds */
          Long startDateTimeInMillis = 1615956275000L;
          Long endDateTimeInMillis = 1615959875000L;
    
          java.util.Calendar calendarStartTime = new GregorianCalendar();
          calendarStartTime.setTimeInMillis(startDateTimeInMillis);
    
          // Time zone info
          TimeZone tz = calendarStartTime.getTimeZone();
          ZoneId zid = tz.toZoneId();
    
          /* Generate unique identifier */
          UidGenerator ug = new RandomUidGenerator();
          Uid uid = ug.generateUid();
    
          /* Create the event */
          String eventSummary = "New Year";
          LocalDateTime start = LocalDateTime.ofInstant(calendarStartTime.toInstant(), zid);
          LocalDateTime end = LocalDateTime.ofInstant(Instant.ofEpochMilli(endDateTimeInMillis), zid);
          VEvent event = new VEvent(start, end, eventSummary);
          event.add(uid);
    
          // Add email addresses as attendees
          Attendee attendee1 = new Attendee("danny@example.com");
          Attendee attendee2 = new Attendee("jenifer@example.com");
          event.add(attendee1);
          event.add(attendee2);
    
          // Create an Organizer
          Organizer organizer = new Organizer();
          organizer.setValue("MAILTO:sender@example.com");
          event.add(organizer);
    
          /* Create calendar */
          Calendar icsCalendar = new Calendar();
          icsCalendar.add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
    		
          // Set the location
          Location location = new Location("Conference Room");
    
          // Add the Location to the event
          event.add(location);
    
          /* Add event to calendar */
          icsCalendar.add(event);
    
          /* Create a file */
          String filePath = "my_meeting.ics";
          FileOutputStream out = null;
          try {
    
    	   out = new FileOutputStream(filePath);
    	   CalendarOutputter outputter = new CalendarOutputter();
    	   outputter.output(icsCalendar, out);
    
          } catch (FileNotFoundException e) {
    	   e.printStackTrace();
          } catch (ValidationException e) {
    	   e.printStackTrace();
          } catch (IOException e) {
    	   e.printStackTrace();
          } finally {
    		 if (out != null) {
    		      try {
    		           out.close();
    		      } catch (IOException e) {
    		           e.printStackTrace();
    		      }
                     }
          }
    
       }
    }
    

    Here's another example of Spring Boot REST controller that includes an API for generating and downloading an ICS (iCalendar) file:

    import java.time.Instant;
    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.util.GregorianCalendar;
    import java.util.TimeZone;
    import org.springframework.core.io.ByteArrayResource;
    import org.springframework.core.io.Resource;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import net.fortuna.ical4j.model.Calendar;
    import net.fortuna.ical4j.model.component.VEvent;
    import net.fortuna.ical4j.model.property.Attendee;
    import net.fortuna.ical4j.model.property.Location;
    import net.fortuna.ical4j.model.property.Organizer;
    import net.fortuna.ical4j.model.property.ProdId;
    import net.fortuna.ical4j.model.property.Uid;
    import net.fortuna.ical4j.util.RandomUidGenerator;
    import net.fortuna.ical4j.util.UidGenerator;
    
    @RestController
    @RequestMapping(path = "/rest/api")
    public class ExampleController {
    
       @GetMapping(path = "/generate-calendar")
       public ResponseEntity<Resource> generateCalenderFile() {
    
          /* Event start and end time in milliseconds */
          Long startDateTimeInMillis = 1615956275000L;
          Long endDateTimeInMillis = 1615959875000L;
    
          java.util.Calendar calendarStartTime = new GregorianCalendar();
          calendarStartTime.setTimeInMillis(startDateTimeInMillis);
    
          // Time zone info
          TimeZone tz = calendarStartTime.getTimeZone();
          ZoneId zid = tz.toZoneId();
    
          /* Generate unique identifier */
          UidGenerator ug = new RandomUidGenerator();
          Uid uid = ug.generateUid();
    
          /* Create the event */
          String eventSummary = "New Year";
          LocalDateTime start = LocalDateTime.ofInstant(calendarStartTime.toInstant(), zid);
          LocalDateTime end = LocalDateTime.ofInstant(Instant.ofEpochMilli(endDateTimeInMillis), zid);
          VEvent event = new VEvent(start, end, eventSummary);
          event.add(uid);
    
          // Add email addresses as attendees
          Attendee attendee1 = new Attendee("danny@example.com");
          Attendee attendee2 = new Attendee("jenifer@example.com");
          event.add(attendee1);
          event.add(attendee2);
    
          // Create an Organizer
          Organizer organizer = new Organizer();
          organizer.setValue("MAILTO:sender@example.com");
          event.add(organizer);
    
          /* Create calendar */
          Calendar icsCalendar = new Calendar();
          icsCalendar.add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
    
          // Set the location
          Location location = new Location("Conference Room");
    
          // Add the Location to the event
          event.add(location);
    
          /* Add event to calendar */
          icsCalendar.add(event);
    
          byte[] calendarByte = icsCalendar.toString().getBytes();
          Resource resource = new ByteArrayResource(calendarByte);
    
          HttpHeaders header = new HttpHeaders();
          header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=mycalendar.ics");
          header.add("Cache-Control", "no-cache, no-store, must-revalidate");
          header.add("Pragma", "no-cache");
          header.add("Expires", "0");
    
          return ResponseEntity.ok().headers(header).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
       }
    
    }