Java read file line by line example program

  • Reading a text file line by line in java can be done by using java.io.BufferedReader .
  • Create a BufferedReader class by passing new FileReader(new File("filename")) object to it's constructor.
  • By using readLine() method of  BufferedReader class we can read line by line text from a text file as Strings.
  • Lets see a java example program on hoe to read data from file line by line using BufferedReader class readLine() method.
  • Java read lines from text file example program.


#1: Java Example program to read file line by line

 

  1. package com.instanceofjava.readfile;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. /** *  * 
  8. @author www.instanceofjava.com 
  9. * @category: Interview Programs 
  10. * @description: How to read text file line by line in java example program 
  11. * */
  12.  
  13. public class ReadFile {
  14.  
  15.     public static void main(String[] args) {        
  16.         
  17.         try {            
  18.            File fileName = new File("E:\\data.txt");
  19.             FileReader fileReader = new FileReader(fileName);     
  20.             BufferedReader bufferedreader = new BufferedReader(fileReader);           
  21.             StringBuffer sb = new StringBuffer();
  22.             String strLine;            
  23.            while ((strLine = bufferedreader.readLine()) != null) {
  24.                 sb.append(strLine);
  25.                 sb.append("\n");        
  26.             }         
  27.            fileReader.close();
  28.            System.out.println(sb.toString()); 
  29.          } catch (IOException e) {
  30.             e.printStackTrace();     
  31.    }
  32.  
  33.     }
  34.  
  35. }

Output:

  1. java read file line by line example
  2. java read file line by line java 8
  3. java read lines from text file 
  4. example bufferedreader java example

#2: Java example program to read text file line by line using java 7 try with resource example



read file line by line java


#3: Java example program to read text file line by line using java 8 example (Using stream)

  1. package com.instanceofjava.readfile;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.nio.file.Paths;
  5. import java.util.stream.Stream;
  6. /**
  7.  *
  8. * @author www.instanceofjava.com
  9.  * @category: Interview Programs 
  10. * @description: How to read text file line by line in java example program using java 8 stream
  11. */
  12. public class ReadFile {
  13. public static void main(String[] args) throws IOException {
  14.  
  15. try (Stream<String> stream = Files.lines(Paths.get("E:\\data.txt"))) 
  16. {           
  17.  
  18.  stream.forEach(System.out::println);
  19.  
  20. }
  21. }
  22. }

Convert to maven project in eclipse java

  • In order to convert any java project in to maven using eclipse we need to install m2e plugin.
  • Latest versions of eclipse are coming with this m2e plugin by default.
  • If not found this plugin we can install it by help->install->click on add and enter http://download.eclipse.org/technology/m2e/releases. 
  • currently i am using eclipse oxygen version so it is having m2e plugin.
  • I have created a normal java project and i want to convert that into a maven project.
  • To convert any project in to maven right click on the project and ->configure->convert to maven project. 
  • After that a window will be opened and you need to enter group id and artifact id and then click on finish.  
  • convert to maven project eclipse luna / convert to maven project is not visible in eclipse /convert to maven project option not available in eclipse.



Right click on project and select configure-> convert to maven project.


convert to maven project java

Project will be converted to maven by creating pom.xml file.

how to convert to maven project java

 

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.or
  2. /2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  3. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.   <modelVersion>4.0.0</modelVersion>
  5.   <groupId>com.instanceofjava.maven</groupId>
  6.   <artifactId>MavenProject</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <build>
  9.     <sourceDirectory>src</sourceDirectory>
  10.     <plugins>
  11.       <plugin>
  12.         <artifactId>maven-compiler-plugin</artifactId>
  13.         <version>3.7.0</version>
  14.         <configuration>
  15.           <source>1.8</source>
  16.           <target>1.8</target>
  17.         </configuration>
  18.       </plugin>
  19.     </plugins>
  20.   </build>
  21. </project>

Add dependencies to your pom.xml file

  1.  <properties>
  2.         <springVersion>5.0.3.RELEASE</springVersion>
  3.       </properties>
  4.       <dependencies>
  5.         <dependency>
  6.           <groupId>org.springframework</groupId>
  7.           <artifactId>spring-context</artifactId>
  8.           <version>${springVersion}</version>
  9.         </dependency>
  10.        <dependency>
  11.          <groupId>org.springframework</groupId>
  12.          <artifactId>spring-core</artifactId>
  13.           <version>5.0.3.RELEASE</version>
  14.         </dependency>
  15.       </dependencies>

How to read values from properties file in java example

  • To store configurable parameters, .properties file will be used in java.
  • We can Store data in key value pair (key=value).
  • Re compilation not required if we change any keys or values in properties file.
  • Used for internationalization  and to store frequently changeable values. 
  • java.util.Properties class is sub class of Hashtable. 
  • We can read / load the propertied file using InputStream.
  • InputStream inputStream = getClass().getClassLoader().getResourceAsStream(properties_FileName);
  • Create a maven project, under resources create one .properties file and load this file in main class using getClass().getClassLoader().getResourceAsStream(properties_FileName).
  • Lets see an example java program on java read properties file from resource folder or how to read values from properties file in java example or how to get values from properties file in java.

 #1: Create a maven project:

java read properties file from classpath


Create properties file:

reading properties file in java

#1: Java example program  to get values from properties file in java

  1. package com.instanceofjava.propertiesfile;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.Date;
  6. import java.util.Properties;
  7. /**
  8.  *  
  9. * @author www.instanceofjava.com
  10.  * @category: java example programs
  11.  *  
  12. * Write a java example program to read/ load properties file
  13.  *
  14.  */
  15. public class ReadPropertiesFile {
  16.  
  17.     public Properties getProperties() throws IOException {
  18.         
  19.         InputStream inputStream=null;
  20.         Properties properties = new Properties();
  21.         try {
  22.             
  23.             String propFileName = "config.properties";
  24.  
  25.             inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
  26.  
  27.             if (inputStream != null) {
  28.                 properties.load(inputStream);
  29.             } else {
  30.                 throw new FileNotFoundException("property file '" + propFileName + "' not found
  31. in the classpath");
  32.             }
  33.  
  34.  
  35.         } catch (Exception e) {
  36.             System.out.println("Exception: " + e);
  37.        } finally {
  38.             inputStream.close();
  39.         }
  40.          return properties;
  41.     }
  42.     
  43.     
  44.     public static void main(String[] args) throws IOException {
  45.         
  46.         ReadPropertiesFile obj= new ReadPropertiesFile();
  47.         Properties properties=obj.getProperties();
  48.         // get the each property value using getProperty() method 
  49.         System.out.println("username: "+properties.getProperty("username"));
  50.         System.out.println("password: "+properties.getProperty("password"));
  51.         System.out.println("url: "+properties.getProperty("url"));
  52.         
  53.                 
  54.     }
  55.  
  56. }

Output:

  1. username: user1
  2. password: abc123
  3. url: www.instanceofjava.com

Java finally block after return statement

  • finally block will be executed always even exception occurs.
  • If we explicitly call System.exit() method then only finally block will not be executed if exit() call is before finally block.
  • There are few more rare scenarios where finally block will not be executed.
  1. When JVM crashes
  2. When there is an infinite loop
  3. When we kill the process ex:kill -9 (on unix)
  4. Power failure, hardware error or system crash.
  5. And as we discussed System.exit().
  •  Other than these conditions finally block will be executed always.
  • finally block is meant to keep cleaning of resources. Placing code other than cleaning is a bad practice
  • What happens if we place finally block after return statement? or
  • Does finally block will execute after return statement??
  •  As per the above rules Yes finally will always execute except any interruption like System.exit()  or all above mentioned conditions

 Program #1 : Java example program which explains how finally block will be executed even after a return statement in a method.

  1. package com.instanceofjava.finallyblockreturn;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: does finally gets executed after return statement??
  5.  *
  6.  */
  7. public class FinallyBlockAfterReturn {
  8.  
  9.     public static int Calc(){
  10.         try {
  11.             
  12.             return 0;
  13.         } catch (Exception e) {
  14.             return 1;
  15.         }
  16.  
  17. finally{
  18.             
  19.  System.out.println("finally block will be executed even when we
  20. place after return statement");
  21.         }
  22.  }
  23.     
  24. public static void main(String[] args) {
  25.         
  26.         System.out.println(Calc());         
  27. }
  28.  
  29. }



  
Output:


  1. finally block will be executed even when we place after return statement
  2. 0


 Can we place return statement in finally??
  • Yes we can place return statement in finally and finally block return statement will be executed.
  • But it is a very bad practice to place return statement in finally block.
Program #2 : Java example program which explains finally block with return statement in a method.



finally block after return statement

How to subtract minutes from current time in java



Program #1 : Java Example Program to subtract minutes from given string formatted date time using java 8.


  1. package java8;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: how to subtract minutes from date time using java 8  
  5. *
  6.  */
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9.  
  10. public class SubtractMinutesJava{

  11. public static void main(String[] args) {
  12.  
  13.   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  14.  
  15.         String currentTime= "2017-10-19 22:00:00";

  16.  
  17.         System.out.println("Before subtraction of minutes from date: "+currentTime);
  18.  
  19.         LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
  20.  
  21.         datetime=datetime.minusMinutes(30);
  22.  
  23.         String aftersubtraction=datetime.format(formatter);
  24.         System.out.println("After 30 minutes subtraction from date: "+aftersubtraction);

  25.  
  26.     }
  27.  
  28. }

Output:

  1. Before subtraction of minutes from date: 2017-10-19 22:00:00
  2. After 30 minutes subtraction from date: 2017-10-19 21:30:00

Program #2 : Java Example Program to subtract seconds from given string formatted date time using java 8.
  1. package java8;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: how to subtract seconds from date time using java 8  
  5. *
  6.  */
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9.  
  10. public class SubtractSecondsJava{

  11. public static void main(String[] args) {
  12.  
  13.   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  14.  
  15.         String currentTime= "2017-10-19 22:00:00";

  16.  
  17.         System.out.println("Before subtraction of seconds from date time: "+currentTime);
  18.  
  19.         LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
  20.  
  21.         datetime=datetime.minusSeconds(30);
  22.  
  23.         String aftersubtraction=datetime.format(formatter);
  24.         System.out.println("After 30 seconds subtraction from date time: "+aftersubtraction);

  25.  
  26.     }
  27.  
  28. }

Output:

  1. Before subtraction of seconds from date time: 2017-10-19 22:00:00
  2. After 30 seconds subtraction from date time: 2017-10-19 21:59:30

Program #3 : Java Example Program to subtract seconds from current date time using java 8.


how to subtract minutes from java date time

How to subtract N hours from current date time using java 8

  • We have already seen how to subtract number of days from java using calendar and using java 8.
  • How to subtract X days from a date using Java calendar and with java 8 
  • Now we will discuss here how to subtract hours from java 8 localdatetime.
  • Some times we will get out date time in string format so we will convert our string format date to java 8 LocaDateTime object.
  • We can user DateTimeFormatter to tell the format of date time to LocalDateTime class.
  • LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
  • LocalDateTime has minusHours(numberOfHours) method to subtract hours from date time.
  • Lets see an example java program to subtract hours from java date time using java 8 LocalDateTime class.
  • How to subtract hours from java 8 date time.



Program #1 : Java Example Program to subtract hours from given string formatted date time using java 8.



  1. package java8;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: how to subtract hours from date time using java 8  
  5. *
  6.  */
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9.  
  10. public class SubstractHoursJava{
  11. public static void main(String[] args) {
  12.  
  13.   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  14.  
  15.         String currentTime= "2017-10-19 22:00:00";
  16.  
  17.         System.out.println("Before subtraction of hours from date: "+currentTime);
  18.  
  19.         LocalDateTime datetime = LocalDateTime.parse(currentTime,formatter);
  20.  
  21.         datetime=datetime.minusHours(4);
  22.  
  23.         String aftersubtraction=datetime.format(formatter);
  24.         System.out.println("After 4 hours subtraction from date: "+aftersubtraction);
  25.  
  26.     }
  27.  
  28. }

Output:

  1. Before subtraction of hours from date: 2017-10-19 22:00:00
  2. After 4 hours subtraction from date: 2017-10-19 18:00:00

  • Now we will see how to subtract one hour from current date time in java using java 8 

Program #2 : Java Example Program to subtract one hour from given current date time using java 8.

  1. package java8;
  2. /**
  3.  * By: www.instanceofjava.com
  4.  * program: how to subtract hours from date time using java 8  
  5. *
  6.  */
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9.  
  10. public class SubtractOneHour {
  11.  
  12. public static void main(String[] args) {
  13.  
  14.   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd H:mm:ss");
  15.  
  16.         LocalDateTime datetime = LocalDateTime.now();
  17.         System.out.println("Before subtraction of hours from date: "+datetime.format(formatter));
  18.  
  19.        datetime=datetime.minusHours(1);
  20.        String aftersubtraction=datetime.format(formatter);
  21.        System.out.println("After 1 hour subtraction from date: "+aftersubtraction);
  22.  
  23.     }
  24.  
  25. }
Output:


  1. Before subtraction of hours from date: 2017-10-19 23:14:12
  2. After 1 hour subtraction from date: 2017-10-19 22:14:12

subtract hours from java date time

C program to insert an element in an array

  • Program to insert an element in an array at a given position
  • C program to insert an element in an array without using function



Program #1: Write a c program to insert an element in array without using function


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6.   int insarray[100], pos, c, n, value;
  7.  
  8.   printf("Enter number of elements of array\n");
  9.    scanf("%d", &n);
  10.  
  11.    printf("Enter all %d elements\n", n);
  12.  
  13.    for (c = 0; c < n; c++)
  14.       scanf("%d", &insarray[c]);
  15.  
  16.    printf("Enter the specific position where you wish to insert an element in array\n");
  17.    scanf("%d", &pos);
  18.  
  19.    printf("Enter the value to insert\n");
  20.    scanf("%d", &value);
  21.  
  22.    for (c = n - 1; c >= pos - 1; c--)
  23.       insarray[c+1] = insarray[c];
  24.  
  25.    insarray[pos-1] = value;
  26.  
  27.    printf("Resultant array is\n");
  28.  
  29.    for (c = 0; c <= n; c++)
  30.       printf("%d\n", insarray[c]);
  31.  
  32. getch();
  33. }
Output:

insert element in array c
Select Menu