Posts

Showing posts from July, 2021

How to read a file on the classpath in Java

Image
There are often programming situations when you need to read a file on the classpath via Java. In this article, I will show you how to write code for this. Reading a file on the classpath Let us first take a look at the code that you need to write to read a file on the classpath. public class ReadFileFromClassPathDemo { public static void main(String[] args) throws IOException { // read in the file from the resources directory ClassLoader classLoader = ReadFileFromClassPathDemo.class.getClassLoader(); URL url = classLoader.getResource("input.txt"); String fileName = url.getFile(); File file = new File(fileName); String str = new String(Files.readAllBytes(file.toPath())); System.out.println(str); }} Java has an in-built class called ClassLoader .  It is used to dynamically load classes. It can also be used to load resources from the classpath. The code above first obtains a ClassLoader . It then invokes the getResource method on the classLoader . This l

How to use Flyway with Spring Boot with code samples

Image
At its core, Flyway is a version control system for databases. It allows applying incremental changes to a database. In this article, we will be learning how to use Flyway with a Spring Boot application. Flyway Overview As explained earlier, Flyway is a version control system for databases. To explain in very simple words, it allows specifying database DDL/DML in an SQL file (also known as a migration). It then applies these changes to the database. In case you need to apply further changes, you need to specify another migration with a higher version number with the incremental changes. Flyway then applies the new changes to the database. Let us now understand how to use Flyway with Spring Boot and a MySQL database. Project Creation and Setup  Step 1 – Create a new Maven Project  (Refer to  this  blog post). This should create a project as shown below: Step 2 – Add the Spring Boot, Flyway, and MySQL dependencies . So, the  pom.xml  file should be similar to the following: <project x