How do I create XLSX files using Apache POI?

First of all, make sure that you have the Apache POI library included in your project. If you are using Maven, you can add the following to your pom.xml:

Maven Dependencies

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.5</version>
</dependency>

Maven Central

Then, you can use the following code to create an Excel .xlsx file:

package org.kodejava.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelExample {
    public static void main(String[] args) {
        // Create a new Workbook
        Workbook workbook = new XSSFWorkbook();

        // Create a new sheet in the workbook with a name
        Sheet sheet = workbook.createSheet("MySheet");

        // Create a row at index 0
        Row row = sheet.createRow(0);

        // Create a cell at index 0
        Cell cell = row.createCell(0, CellType.STRING);
        // Assign the string "Hello" to the cell
        cell.setCellValue("Hello");

        // Add some other rows and cells similarly...
        // ...

        try (FileOutputStream fos = new FileOutputStream("MyExcel.xlsx")) {
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Excel file has been generated!");

        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This program will create an Excel .xlsx file named MyExcel.xlsx with a single sheet called “MySheet.” The sheet has a single cell in the first row which contains the string “Hello.” The output file will be generated in the root directory of your project.

The above-given code is only a basic example. Apache POI allows advanced features like applying styles to cells, merging cells, and working with formulas among others. The library also supports other Microsoft Office file formats.

Here is another slightly more complex example where we create multiple rows and cells:

package org.kodejava.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelAnotherExample {
    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Students");

        Row rowHeader = sheet.createRow(0);
        Cell cellHeader1 = rowHeader.createCell(0, CellType.STRING);
        cellHeader1.setCellValue("ID");

        Cell cellHeader2 = rowHeader.createCell(1, CellType.STRING);
        cellHeader2.setCellValue("Name");

        for(int i = 1; i < 6; i++) {
            Row rowData = sheet.createRow(i);

            Cell cellData1 = rowData.createCell(0, CellType.NUMERIC);
            cellData1.setCellValue(i);

            Cell cellData2 = rowData.createCell(1, CellType.STRING);
            cellData2.setCellValue("Student " + i);
        }

        try (FileOutputStream fos = new FileOutputStream("StudentsData.xlsx")) {
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Excel file has been generated!");

        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This code creates an Excel file named StudentsData.xlsx with a single worksheet. The worksheet contains a listing of student names and their respective IDs. The first row is a header with “ID” and “Name” labels. The next rows contain the IDs (numeric) and names (string “Student X”) for five different students.

How do I compile and execute a JDK preview features with Maven?

To compile and execute a JDK preview features with Maven, you need to add in the following configurations in your pom.xml file:

  • Compiler Plugin: The configuration should specify the JDK version and enable the preview features. It should look similar to this:
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <release>21</release>
                <compilerArgs>--enable-preview</compilerArgs>
            </configuration>
        </plugin>
    </plugins>
</build>
  • Surefire Plugin: If you’re using the Maven Surefire Plugin to run your tests, you should also enable the preview features there. The configuration may look similar to this:
<build>
    <plugins>
    ...
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>
                <argLine>--enable-preview</argLine>
            </configuration>
        </plugin>
    </plugins>
</build>

Before building your project, ensure that you have JDK 21-preview installed on your computer, and it’s properly set in JAVA_HOME environment variable or in the IDE settings.

Then use Maven to package or install your project:

mvn clean package
# or
mvn clean install

Please ensure that you have the correct version of maven-compiler-plugin and maven-surefire-plugin that support the JDK 21-preview features. For the project that uses Spring MVC, you should make sure all dependencies are compatible with JDK 21-preview as well.

How do I sum object property using Stream API?

If you have a collection of objects and want to sum one of their properties using the Java Stream API, you need to use the map() function to convert each object into the value of its property and then use the reduce() function to sum all the values.

Here is an example where we have a Person class with age property, and we want to get the sum of ages for a list of Person objects:

package org.kodejava.basic;

public class Person {
    private final int age;

    // Constructor, getters, and setters...
    public Person(int age) {
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }
}
package org.kodejava.basic;

import java.util.Arrays;
import java.util.List;

public class PropertySumDemo {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person(20),
                new Person(30),
                new Person(40));

        int totalAge = people.stream()
                .mapToInt(Person::getAge)
                .sum();

        System.out.println(totalAge);  // Outputs: 90
    }
}

In this example, mapToInt(Person::getAge) converts each Person object in the people stream into an int representing their age. The sum() function then adds up these ages, resulting in the total age.

How to Read a File in Java: A Comprehensive Tutorial

In this Tutorial, we will learn about how to read a file in Java. File manipulation is a fundamental aspect of programming, especially when dealing with data processing and storage. Java provides robust libraries and classes to handle file operations efficiently. In this in-depth tutorial, we will explore the various techniques and best practices for reading files in Java.

Understanding File Processing in Java

Before delving into file reading techniques, it’s crucial to understand the basics of file processing in Java. Files are represented by the java.io.File class, which encapsulates the path to a file or directory. Java offers multiple classes like FileReader, BufferedReader, and Scanner to facilitate reading operations.

Reading Text Files Using FileReader and BufferedReader

Using FileReader and BufferedReader Classes

The FileReader class is used for reading character files. It works at the byte level, reading streams of characters. BufferedReader class, on the other hand, reads text from a character-input stream, buffering characters to provide efficient reading.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TextFileReader {
    public static void main(String[] args) {
        String filePath = "example.txt";
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we read a text file line by line using FileReader wrapped in a BufferedReader.

Reading CSV Files Using Scanner Class

CSV files are widely used for storing tabular data. Java’s Scanner class simplifies the process of reading from various sources, including files. Let’s see how we can read data from a CSV file.

Reading CSV File Using Scanner

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CSVFileReader {
    public static void main(String[] args) {
        String filePath = "data.csv";

        try (Scanner scanner = new Scanner(new File(filePath))) {
            scanner.useDelimiter(",");

            while (scanner.hasNext()) {
                System.out.print(scanner.next() + " ");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

In this example, the Scanner reads the CSV file and separates values using a comma (,).

Best Practices and Error Handling

Handling Exceptions

When dealing with file operations, exceptions such as FileNotFoundException and IOException must be handled properly to ensure graceful error recovery and prevent application crashes.

Using Try-With-Resources

Java 7 introduced the try-with-resources statement, which ensures that each resource is closed at the end of the statement. It simplifies resource management and reduces the chance of resource leaks and related issues.

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
    // Read file content here
} catch (IOException e) {
    e.printStackTrace();
}

Conclusion

In this extensive tutorial, we explored various techniques for reading files in Java, ranging from basic text files to more complex CSV files. Understanding the classes and methods provided by Java’s I/O packages is essential for effective file processing.

Remember to handle exceptions diligently and use try-with-resources to manage resources efficiently. With the knowledge gained from this tutorial, you can confidently read and manipulate files in your Java applications, ensuring smooth and reliable data processing.

By incorporating these practices and techniques into your Java projects, you are well-equipped to handle a wide array of file-reading scenarios, making your applications more versatile and robust. If you face any problem to read a file using java programming then you can search for Java assignment help. Happy coding

How do I iterate through date range in Java?

The following code snippet shows you how to iterate through a range of dates in Java. We use the Java Date Time API. We do increment and decrement iteration using a simple for loop.

Here are the steps:

  • We declare the start and end date of the loop, the dates are instance of java.time.LocalDate.
  • Create a for loop.
  • In the for loop we set the initialization variable the start date.
  • The loop executed if the date is less than end date, using the isBefore() method, otherwise it will be terminated.
  • The date will be incremented by 1 on each loop.
package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;

public class DateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        System.out.println("Start = " + start);
        System.out.println("End   = " + end);
        System.out.println("--------------------");

        for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
            System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek());
        }

        System.out.println("--------------------");

        for (LocalDate date = end; date.isAfter(start); date = date.minusDays(1)) {
            System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek()
                    .getDisplayName(TextStyle.SHORT, Locale.getDefault()));
        }
    }
}

Running the code snippet gives you the following output:

Start = 2023-10-01
End   = 2023-10-08
--------------------
Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY
--------------------
Date 10/08/23 is Sun
Date 10/07/23 is Sat
Date 10/06/23 is Fri
Date 10/05/23 is Thu
Date 10/04/23 is Wed
Date 10/03/23 is Tue
Date 10/02/23 is Mon

Next, we are going to use while loop.

  • Define the start and end date to loop
  • We increment the start date by 1 day.
  • Execute the loop if the start date is before end date.
package org.kodejava.datetime;

import java.time.LocalDate;

public class WhileDateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1).minusDays(1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        while ((start = start.plusDays(1)).isBefore(end)) {
            System.out.printf("Date %tD is %s%n", start, start.getDayOfWeek());
        }
    }
}

The result of the code snippet above is:

Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY

To use the Java stream, we can do it like the following code snippet:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.stream.Stream;

public class StreamDateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        Stream.iterate(start, date -> date.plusDays(1))
                .limit(ChronoUnit.DAYS.between(start, end))
                .forEach(date -> {
                    System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek());
                });
    }
}

The result of the code snippet above is:

Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY

From Java 9 we can use LocalDate.datesUntil() method. It will iterate from the date to the specified end date by increment step of 1 day or the specified increment of Period.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.Period;

public class DatesUntilDateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        start.datesUntil(end).forEach(date -> {
            System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek());
        });

        start.datesUntil(end, Period.ofDays(2)).forEach(System.out::println);
    }
}

Running the code snippet produces the following result:

Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY
2023-10-01
2023-10-03
2023-10-05
2023-10-07