Read one word java

In this article we will be discussing about ways and techniques to read word documents in Java using Apache POI library. The word document may contain images, tables or plain text. Apart from this a standard word file has header and footers too. Here in the following examples we will be parsing a word document by reading its different paragraph, runs, images, tables along with headers and footers. We will also take a look into identifying different styles associated with the paragraphs such as font-size, font-family, font-color etc.

Maven Dependencies

Following is the poi maven depedency required to read word documents. For latest artifacts visit here

pom.xml

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

Reading Complete Text from Word Document

The class XWPFDocument has many methods defined to read and extract .docx file contents. getText() can be used to read all the texts in a .docx word document. Following is an example.

TextReader.java

public class TextReader {
	
	public static void main(String[] args) {
	 try {
		   FileInputStream fis = new FileInputStream("test.docx");
		   XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
		   XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
		   System.out.println(extractor.getText());
		} catch(Exception ex) {
		    ex.printStackTrace();
		}
 }

}

Reading Headers and Foooters of Word Document

Apache POI provides inbuilt methods to read headers and footers of a word document. Following is an example that reads and prints header and footer of a word document. The example .docx file is available in the source which can be downloaded at the end of thos article.

HeaderFooter.java

public class HeaderFooterReader {

	public static void main(String[] args) {
		
		try {
			FileInputStream fis = new FileInputStream("test.docx");
			XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
			XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(xdoc);

			XWPFHeader header = policy.getDefaultHeader();
			if (header != null) {
				System.out.println(header.getText());
			}

			XWPFFooter footer = policy.getDefaultFooter();
			if (footer != null) {
				System.out.println(footer.getText());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}

Output

This is Header

This is footer

 Other Interesting Posts
Java 8 Lambda Expression
Java 8 Stream Operations
Java 8 Datetime Conversions
Random Password Generator in Java

Read Each Paragraph of a Word Document

Among the many methods defined in XWPFDocument class, we can use getParagraphs() to read a .docx word document paragraph wise.This method returns a list of all the paragraphs(XWPFParagraph) of a word document. Again the XWPFParagraph has many utils method defined to extract information related to any paragraph such as text alignment, style associated with the paragrpahs.

To have more control over the text reading of a word document,each paragraph is again divided into multiple runs. Run defines a region of text with a common set of properties.Following is an example to read paragraphs from a .docx word document.

ParagraphReader.java

public class ParagraphReader {

	public static void main(String[] args) {
		try {
			FileInputStream fis = new FileInputStream("test.docx");
			XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));

			List paragraphList = xdoc.getParagraphs();

			for (XWPFParagraph paragraph : paragraphList) {

				System.out.println(paragraph.getText());
				System.out.println(paragraph.getAlignment());
				System.out.print(paragraph.getRuns().size());
				System.out.println(paragraph.getStyle());

				// Returns numbering format for this paragraph, eg bullet or lowerLetter.
				System.out.println(paragraph.getNumFmt());
				System.out.println(paragraph.getAlignment());

				System.out.println(paragraph.isWordWrapped());

				System.out.println("********************************************************************");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

Reading Tables from Word Document

Following is an example to read tables present in a word document. It will print all the text rows wise.

TableReader.java

public class TableReader {

	public static void main(String[] args) {
		try {
			FileInputStream fis = new FileInputStream("test.docx");
			XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
			Iterator bodyElementIterator = xdoc.getBodyElementsIterator();
			while (bodyElementIterator.hasNext()) {
				IBodyElement element = bodyElementIterator.next();

				if ("TABLE".equalsIgnoreCase(element.getElementType().name())) {
					List tableList = element.getBody().getTables();
					for (XWPFTable table : tableList) {
						System.out.println("Total Number of Rows of Table:" + table.getNumberOfRows());
						for (int i = 0; i < table.getRows().size(); i++) {

							for (int j = 0; j < table.getRow(i).getTableCells().size(); j++) {
								System.out.println(table.getRow(i).getCell(j).getText());
							}
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

Reading Styles from Word Document

Styles are associated with runs of a paragraph. There are many methods available in the XWPFRun class to identify the styles associated with the text.There are methods to identify boldness, highlighted words, capitalized words etc.

StyleReader.java

public class StyleReader {

	public static void main(String[] args) {
		try {
			FileInputStream fis = new FileInputStream("test.docx");
			XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));

			List paragraphList = xdoc.getParagraphs();

			for (XWPFParagraph paragraph : paragraphList) {

				for (XWPFRun rn : paragraph.getRuns()) {

					System.out.println(rn.isBold());
					System.out.println(rn.isHighlighted());
					System.out.println(rn.isCapitalized());
					System.out.println(rn.getFontSize());
				}

				System.out.println("********************************************************************");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}

Reading Image from Word Document

Following is an example to read image files from a word document.

public class ImageReader {

	public static void main(String[] args) {

		try {
			FileInputStream fis = new FileInputStream("test.docx");
			XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
			List pic = xdoc.getAllPictures();
			if (!pic.isEmpty()) {
				System.out.print(pic.get(0).getPictureType());
				System.out.print(pic.get(0).getData());
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Download source

The Java IO API provides two kinds of interfaces for reading files, streams and readers. The streams are used to read binary data and readers to read character data. Since a text file is full of characters, you should be using a Reader implementations to read it. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability. 

You can also use both BufferedReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.

The JDK 7 also introduces a couple of nice utility e.g. Files class and try-with-resource construct which made reading a text file, even more, easier.

In this article, I am going to share a couple of examples of reading a text file in Java with their pros, cons, and important points about each approach. This will give you enough detail to choose the right tool for the job depending on the size of file, the content of the file, and how you want to read.

1. Reading a text file using FileReader

The FileReader is your general-purpose Reader implementation to read a file. It accepts a String path to file or a java.io.File instance to start reading. It also provides a couple of overloaded read() methods to read a character or read characters into an array or into a CharBuffer object. 

Here is an example of reading a text file using FileReader in Java:

public static void readTextFileUsingFileReader(String fileName) {
    try {
      FileReader textFileReader = new FileReader(fileName);
      char[] buffer = new char[8096];
      int numberOfCharsRead = textFileReader.read(buffer);
      while (numberOfCharsRead != -1) {
        System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));
        numberOfCharsRead = textFileReader.read(buffer);
      }
      textFileReader.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

Output
Once upon a time, we wrote a program to read data from a text file.
The program failed to read a large file but then Java 8 come to
rescue, which made reading file lazily using Streams. 

You can see that instead of reading one character at a time, I am reading characters into an array. This is more efficient because read() will access the file several times but read(char[]) will access the file just one time to read the same amount of data.

I am using an 8KB of the buffer, so in one call I am limited to read that much data only. You can have a bigger or smaller buffer depending upon your heap memory and file size. You should also notice that I am looping until read(char[]) returns -1 which signals the end of the file.

Another interesting thing to note is to call to String.valueOf(buffer, 0, numberOfCharsRead), which is required because you might not have 8KB of data in the file or even with a bigger file, the last call may not be able to fill the char array and it could contain dirty data from the last read.

2. Reading a text file in Java using BufferedReader

The BufferedReader class is a Decorator which provides buffering functionality to FileReader or any other Reader. This class buffer input from source e.g. files into memory for the efficient read. In the case of BufferedReader, the call to read() doesn’t always goes to file if it can find the data in the internal buffer of BufferedReader.

The default size of the internal buffer is 8KB which is good enough for most purpose, but you can also increase or decrease buffer size while creating BufferedReader object. The reading code is similar to the previous example.

public static void readTextFileUsingBufferdReader(String fileName) {
    try {
      FileReader textFileReader = new FileReader(fileName);
      BufferedReader bufReader = new BufferedReader(textFileReader);

      char[] buffer = new char[8096];

      int numberOfCharsRead = bufReader.read(buffer); // read will be from
      // memory
      while (numberOfCharsRead != -1) {
        System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));
        numberOfCharsRead = textFileReader.read(buffer);
      }

      bufReader.close();

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

Output
[From File] Java provides several ways to read file

In this example as well, I am reading the content of the file into an array. Instead of reading one character at a time, this is more efficient. The only difference between the previous examples and this one is that the read() method of BufferedReader is faster than the read() method of FileReader because read can happen from memory itself.

In order to read the full-text file, you loop until read(char[]) method returns -1, which signals the end of the file. See Core Java Volume 1 — Fundamentals to learn more about how BufferedReader class works in Java.

How to read a text file in Java

3. Reading a text file in Java using Scanner

The third tool or class to read a text file in Java is the Scanner, which was added on JDK 1.5 release. The other two FileReader and BufferedReader are present from JDK 1.0 and JDK 1.1 versions. The Scanner is a much more feature-rich and versatile class. 

It does not just provide reading but the parsing of data as well. You can not only read text data but you can also read the text as a number or float using nextInt() and nextFloat() methods.

The class uses regular expression pattern to determine token, which could be tricky for newcomers. The two main method to read text data from Scanner is next() and nextLine(), former one read words separated by space while later one can be used to read a text file line by line in Java. In most cases, you would use the nextLine() method as shown below:

public static void readTextFileUsingScanner(String fileName) {
    try {
      Scanner sc = new Scanner(new File(fileName));
      while (sc.hasNext()) {
        String str = sc.nextLine();
        System.out.println(str);
      }
      sc.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Output
[From File] Java provides several ways to read the file.

You can use the hasNext() method to determine if there is any more token left to read in the file and loop until it returns false. Though you should remember that next() or nextLine() may block until data is available even if hasNext() return true. This code is reading the content of «file.txt» line by line. See this tutorial to learn more about the Scanner class and file reading in Java.

4. Reading a text file using Stream in Java 8

The JDK 8 release has brought some cool new features e.g. lambda expression and streams which make file reading even smoother in Java. Since streams are lazy, you can use them to read-only lines you want from the file e.g. you can read all non-empty lines by filtering empty lines. The use of method reference also makes the file reading code much more simple and concise, so much so that you can read a file in just one line as shown below:

Files.lines(Paths.get("newfile.txt")).forEach(System.out::println);

Output
This is the first line of file

something is better than nothing

this is the last line of the file

Now, if you want to do some pre-processing, here is code to trim each line, filter empty lines to only read non-empty ones, and remember, this is lazy because Files.lines() method return a stream of String and Streams are lazy in JDK 8 (see Java 8 in Action).

Files.lines(new File("newfile.txt").toPath())
.map(s -> s.trim()) 
.filter(s -> !s.isEmpty()) 
.forEach(System.out::println);

We’ll use this code to read a file that contains a line that is full of whitespace and an empty line, the same one which we have used in the previous example, but this time, the output will not contain 5 line but just three lines because empty lines are already filtered, as shown below:

Output
This is the first line of file
something is better than nothing
this is the last line of the file

You can see only three out of five lines appeared because the other two got filtered. This is just the tip of the iceberg on what you can do with Java SE 8, See Java SE 8 for Really Impatient to learn more about Java 8 features.

Reading text file in Java 8 example

5. How to read a text file as String in Java

Sometimes you read the full content of a text file as String in Java. This is mostly the case with small text files as for large files you will face java.lang.OutOfMemoryError: java heap space error. Prior to Java 7, this requires a lot of boiler code because you need to use a BufferedReader to read a text file line by line and then add all those lines into a StringBuilder and finally return the String generated from that.

Now you don’t need to do all that, you can use the Files.readAllBytes() method to read all bytes of the file in one shot. Once done that you can convert that byte array into String. as shown in the following example:

public static String readFileAsString(String fileName) {
    String data = "";
    try {
      data = new String(Files.readAllBytes(Paths.get("file.txt")));
    } catch (IOException e) {
      e.printStackTrace();
    }

    return data;
  }
Output
[From File] Java provides several ways to read file

This was a rather small file so it was pretty easy. Though, while using readAllBytes() you should remember character encoding. If your file is not in platform’s default character encoding then you must specify the character doing explicitly both while reading and converting to String. Use the overloaded version of readAllBytes() which accepts character encoding. You can also see how I read XML as String in Java here.

6. Reading the whole file in a List

Similar to the last example, sometimes you need all lines of the text file into an ArrayList or Vector or simply on a List. Prior to Java 7, this task also involves boilerplate e.g. reading files line by line, adding them into a list, and finally returning the list to the caller, but after Java 7, it’s very simple now. You just need to use the Files.readAllLines() method, which returns all lines of the text file into a List, as shown below:

public static List<String> readFileInList(String fileName) {
    List<String> lines = Collections.emptyList();
    try {
      lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return lines;
}

Similar to the last example, you should specify character encoding if it’s different from than platform’s default encoding. You can use see I have specified UTF-8 here. Again, use this trick only if you know that file is small and you have enough memory to hold a List containing all lines of the text file, otherwise your Java program will crash with OutOfMemoryError.

10 Examples to read text file in Java

7. How to read a text file in Java into an array

This example is also very similar to the last two examples, this time, we are reading the contents of the file into a String array. I have used a shortcut here, first, I have read all the lines as List and then converted the list to an array. 

This results in simple and elegant code, but you can also read data into a character array as shown in the first example. Use the read(char[] data) method while reading data into a character array.

Here is an example of reading a text file into String array in Java:

public static String[] readFileIntoArray(String fileName) {
    List<String> list = readFileInList(fileName);
    return list.toArray(new String[list.size()]);
}

This method leverage our existing method which reads the file into a List and the code here is only to convert a list to an array in Java.

8. How to read a file line by line in Java

This is one of the interesting examples of reading a text file in Java. You often need file data as line by line. Fortunately, both BufferedReader and Scanner provide convenient utility method to read line by line. If you are using BufferedReader then you can use readLine() and if you are using Scanner then you can use nextLine() to read file contents line by line. In our example, I have used BufferedReader as shown below:

public static void readFileLineByLine(String fileName) {
    try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
      String line = br.readLine();
      while (line != null) {
        System.out.println(line);
        line = br.readLine();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

Just remember that A line is considered to be terminated by any one of a line feed (‘n’), a carriage return (‘r’), or a carriage return followed immediately by a line feed.

How to read a file line by line in Java

Java Program to read a text file in Java

Here is the complete Java program to read a plain text file in Java. You can run this program in Eclipse provided you create the files used in this program e.g. «sample.txt», «file.txt», and «newfile.txt«. Since I am using a relative path, you must ensure that files are in the classpath. If you are running this program in Eclipse, you can just create these files in the root of the project directory. The program will throw FileNotFoundException or NoSuchFileExcpetion if it is not able to find the files.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/*
 * Java Program read a text file in multiple way.
 * This program demonstrate how you can use FileReader,
 * BufferedReader, and Scanner to read text file,
 * along with newer utility methods added in JDK 7
 * and 8. 
 */

public class FileReadingDemo {

  public static void main(String[] args) throws Exception {

    // Example 1 - reading a text file using FileReader in Java
    readTextFileUsingFileReader("sample.txt");
    
    // Example 2 - reading a text file in Java using BufferedReader
    readTextFileUsingBufferdReader("file.txt");
    
    // Example 3 - reading a text file in Java using Scanner
    readTextFileUsingScanner("file.txt");
    
    // Example 4 - reading a text file using Stream in Java 8
    Files.lines(Paths.get("newfile.txt")).forEach(System.out::println);    
    
    // Example 5 - filtering empty lines from a file in Java 8
    Files.lines(new File("newfile.txt").toPath())
    .map(s -> s.trim()) 
    .filter(s -> !s.isEmpty()) 
    .forEach(System.out::println);
    
    
    // Example 6 - reading a text file as String in Java
    readFileAsString("file.txt");
    
    
    // Example 7 - reading whole file in a List
    List<String> lines = readFileInList("newfile.txt");
    System.out.println("Total number of lines in file: " + lines.size());
    
    // Example 8 - how to read a text file in java into an array
    String[] arrayOfString = readFileIntoArray("newFile.txt");
    for(String line: arrayOfString){
    System.out.println(line);
    }
    
    // Example 9 - how to read a text file in java line by line
    readFileLineByLine("newFile.txt");
    
    // Example 10 - how to read a text file in java using eclipse
    // all examples you can run in Eclipse, there is nothing special about it. 
    
  }

  public static void readTextFileUsingFileReader(String fileName) {
    try {
      FileReader textFileReader = new FileReader(fileName);
      char[] buffer = new char[8096];
      int numberOfCharsRead = textFileReader.read(buffer);
      while (numberOfCharsRead != -1) {
        System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));
        numberOfCharsRead = textFileReader.read(buffer);
      }
      textFileReader.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public static void readTextFileUsingBufferdReader(String fileName) {
    try {
      FileReader textFileReader = new FileReader(fileName);
      BufferedReader bufReader = new BufferedReader(textFileReader);

      char[] buffer = new char[8096];

      int numberOfCharsRead = bufReader.read(buffer); // read will be from
      // memory
      while (numberOfCharsRead != -1) {
        System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));
        numberOfCharsRead = textFileReader.read(buffer);
      }

      bufReader.close();

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public static void readTextFileUsingScanner(String fileName) {
    try {
      Scanner sc = new Scanner(new File(fileName));
      while (sc.hasNext()) {
        String str = sc.nextLine();
        System.out.println(str);
      }
      sc.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public static String readFileAsString(String fileName) {
    String data = "";
    try {
      data = new String(Files.readAllBytes(Paths.get("file.txt")));
    } catch (IOException e) {
      e.printStackTrace();
    }

    return data;
  }

  public static List<String> readFileInList(String fileName) {
    List<String> lines = Collections.emptyList();
    try {
      lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return lines;
  }

  public static String[] readFileIntoArray(String fileName) {
    List<String> list = readFileInList(fileName);
    return list.toArray(new String[list.size()]);

  }

  public static void readFileLineByLine(String fileName) {
    try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
      String line = br.readLine();
      while (line != null) {
        System.out.println(line);
        line = br.readLine();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

I have not printed the output here because we have already gone through that and discuss in respective examples, but you need Java 8 to compile and run this program. If you are running on Java 7, then just remove the example 4 and 5 which uses Java 8 syntax and features and the program should run fine.

That’s all about how to read a text file in Java. We have looked at all major utilities and classes which you can use to read a file in Java like FileReader, BufferedReader, and Scanner. We have also looked at utility methods added on Java NIO 2 on JDK 7 like. Files.readAllLines() and Files.readAllBytes() to read the file in List and String respectively. 

Other Java File tutorials for beginners

  • How to check if a File is hidden in Java? (solution)
  • How to read an XML file in Java? (guide)
  • How to read an Excel file in Java? (guide)
  • How to read an XML file as String in Java? (example)
  • How to copy non-empty directories in Java? (example)
  • How to read/write from/to RandomAccessFile in Java? (tutorial)
  • How to append text to a File in Java? (solution)
  • How to read a ZIP file in Java? (tutorial)
  • How to read from a Memory Mapped file in Java? (example)

Finally, we have also touched new way of file reading with Java 8 Stream, which provides lazy reading and the useful pre-processing option to filter unnecessary lines.

There are several ways present in java to read the text file like BufferReader, FileReader, and Scanner.  Each and every method provides a unique way of reading the text file.

Methods:

  1. Using Files class
  2. Using FileReader class
  3. Using BufferReader class
  4. Using Scanner class

Let’s see each and every method in detail with an example to get a better understanding of the methods to, later on, implement the same to extract the content from a text document.

Method 1: Using Files class

As Java provides java.nio.file. API we can use java.nio.file.Files class to read all the contents of a file into an array. To read a text file we can use the readAllBytes() method of Files class with which using this method, when you need all the file contents in memory as well as when you are working on small files.

Example:

Java

import java.io.IOException;

import java.nio.charset.StandardCharsets;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.List;

public class GFG {

    private static void readUsingClass(String fileName)

        throws IOException

    {

        Path path = Paths.get(fileName);

        byte[] bytes = Files.readAllBytes(path);

        System.out.println(

            "Read text file using Files class");

        @SuppressWarnings("unused")

        List<String> allLines = Files.readAllLines(

            path, StandardCharsets.UTF_8);

        System.out.println(new String(bytes));

    }

    public static void main(String[] args)

        throws IOException

    {

        String fileName

            = "/Users/mayanksolanki/Desktop/file.txt";

        readUsingClass(fileName);

    }

}

Output:

Method 2: Using FileReader class 

We can use java.io.FileReader can be used to read data (in characters) from files. This is a very efficient method to read the file line by line.

Syntax:

FileReader input = new FileReader(String name);

Example:

Java

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class GFG {

    private static void readUsingFileReader(String fileName)

        throws IOException

    {

        File file = new File(fileName);

        FileReader fr = new FileReader(file);

        BufferedReader br = new BufferedReader(fr);

        String line;

        System.out.println(

            "Reading text file using FileReader");

        while ((line = br.readLine()) != null) {

            System.out.println(line);

        }

        br.close();

        fr.close();

    }

    public static void main(String[] args)

        throws IOException

    {

        String fileName

            = "/Users/mayanksolanki/Desktop/file.txt";

        readUsingFileReader(fileName);

    }

}

Output:

Method 3: Using BufferedReader class 

If you want to read the file line by line and If you want to process on that file then you have to use BufferedReader. It is also used for processing the large file, and it supports encoding also. Reading operation is very efficient on BufferReader.

Note: Either specify the size of the BufferReader or keep the size as a Default size of BufferReader which is 8KB.  
 

Syntax:

BufferedReader in = new BufferedReader(Reader in, int size);

Implementation:

Hello I am learning web- development.
I am writing article for GFG.
I am cloud enthusiast.
I am an open-source contributor.

Note: Before starting create a text file by using .txt extension on your local machine and use the path of that file whenever you necessary while practicing. 

Example:

Java

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class GFG {

    private static void

    readUsingBufferedReader(String fileName)

        throws IOException

    {

        File file = new File(fileName);

        FileReader fr = new FileReader(file);

        BufferedReader br = new BufferedReader(fr);

        String line;

        System.out.println(

            "Read text file using BufferedReader");

        while ((line = br.readLine()) != null) {

            System.out.println(line);

        }

        br.close();

        fr.close();

    }

    public static void main(String[] args)

        throws IOException

    {

        String fileName

            = "/Users/mayanksolanki/Desktop/file.txt";

        readUsingBufferedReader(fileName);

    }

}

 Output:

Method 4: Using Scanner class 

If we want to read the document based on some expression & If you want to read the document line by line then we use Scanner class. A Scanner breaks the input into tokens, which by default matches the white space. 

Example :

Java

import java.io.IOException;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.Scanner;

public class GFG {

    private static void readUsingScanner(String fileName)

        throws IOException

    {

        Path path = Paths.get(fileName);

        Scanner scanner = new Scanner(path);

        System.out.println("Read text file using Scanner");

        while (scanner.hasNextLine()) {

            String line = scanner.nextLine();

            System.out.println(line);

        }

        scanner.close();

    }

    public static void main(String[] args)

        throws IOException

    {

        String fileName

            = "/Users/mayanksolanki/Desktop/file.txt";

        readUsingScanner(fileName);

    }

}

Output:

Implementation: 

Here “my_file.txt” is a demo file used for the program demonstrated below where sample lines are as follows:

Hello I am learning web- development.
I am writing article of GFG.
I am cloud enthusiast.
I am an open-source contributor.

Example 1:

Java

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.nio.charset.Charset;

import java.nio.charset.StandardCharsets;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.List;

import java.util.Scanner;

public class read_file {

    private static void readUsingFileReader(String fileName)

        throws IOException

    {

        File file = new File(fileName);

        FileReader fr = new FileReader(file);

        BufferedReader br = new BufferedReader(fr);

        String line;

        System.out.println(

            "Reading text file using FileReader");

        while ((line = br.readLine()) != null) {

            System.out.println(line);

        }

        br.close();

        fr.close();

    }

    private static void

    readUsingBufferedReader(String fileName)

        throws IOException

    {

        File file = new File(fileName);

        FileReader fr = new FileReader(file);

        BufferedReader br = new BufferedReader(fr);

        String line;

        System.out.println(

            "Read text file using BufferedReader");

        while ((line = br.readLine()) != null) {

            System.out.println(line);

        }

        br.close();

        fr.close();

    }

    private static void readUsingScanner(String fileName)

        throws IOException

    {

        Path path = Paths.get(fileName);

        Scanner scanner = new Scanner(path);

        System.out.println("Read text file using Scanner");

        while (scanner.hasNextLine()) {

            String line = scanner.nextLine();

            System.out.println(line);

        }

        scanner.close();

    }

    private static void readUsingClass(String fileName)

        throws IOException

    {

        Path path = Paths.get(fileName);

        byte[] bytes = Files.readAllBytes(path);

        System.out.println(

            "Read text file using Files class");

        @SuppressWarnings("unused")

        List<String> allLines = Files.readAllLines(

            path, StandardCharsets.UTF_8);

        System.out.println(new String(bytes));

    }

    public static void main(String[] args)

        throws IOException

    {

        String fileName

            = "C:\Users\HP\Desktop\my_file.txt";

        readUsingClass(fileName);

        readUsingScanner(fileName);

        readUsingBufferedReader(fileName);

        readUsingFileReader(fileName);

    }

}

 
Example 2: Reading specific lines from a text file

Now If you want to read the specific lines from the given document then we use the BufferReader method. Depending on the file BufferReader() method is used so that our code works faster and efficiently. In this program, the Text file stored in BufferReader is a traverse through all the lines by using for loop, and when if the condition becomes true we will print that lines 

Implementation: 

myfile.txt is the demo file to be used. 

This is the sample lines been contained in this file which is consisting of random arbitral words composed in lines 

3D printing or additive manufacturing is a process of making three dimensional solid objects from a digital file.

The creation of a 3D printed object is achieved using additive processes. In an additive process an object is created by laying down successive layers of material until the object is created. Each of these layers can be seen as a thinly sliced cross-section of the object.

3D printing is the opposite of subtractive manufacturing which is cutting out / hollowing out a piece of metal or plastic with for instance a milling machine.

3D printing enables you to produce complex shapes.

It uses less material than traditional manufacturing methods.

Java

import java.io.*;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class GFG {

    public static void main(String[] args)

    {

        String text = "";

        int lineNumber;

        try {

            FileReader readfile = new FileReader(

                "C:\Users\HP\Desktop\Exam.txt");

            BufferedReader readbuffer

                = new BufferedReader(readfile);

            for (lineNumber = 1; lineNumber < 10;

                 lineNumber++) {

                if (lineNumber == 7) {

                    text = readbuffer.readLine();

                }

                else {

                    readbuffer.readLine();

                }

            }

        }

        catch (IOException e) {

            e.printStackTrace();

        }

        System.out.println(" The specific Line is: "

                           + text);

    }

}

 
Output: The specific Line is:

3D printing enables you to produce complex shapes.

This java example shows how to read the contents of a file word by word.

Source: (ReadWords.java)

import java.util.Scanner;
import java.io.*;
 
public class ReadWords {
  public static void main(String[] args) throws IOException {
 
    File file = new File("words.txt");
    Scanner input = new Scanner(file); 
 
    int count = 0;
    while (input.hasNext()) {
      String word  = input.next();
      System.out.println(word);
      count = count + 1;
    }
    System.out.println("Word count: " + count);
  }
}
 

Output:

$ cat words.txt 
The cat in the hat

$ java ReadWords
The
cat
in
the
hat
Word count: 5

1

2

This is one of the articles from our Java Tutorial for Beginners.


We suggest that you recall two real-world examples which will help you understand the topic of this article.

  1. When we’re about to go on a flight, the staff at the airport first check your luggage with a scanner machine. The machine scans your bag and the airport employee finds out exactly what you have in it.
  2. Scanners in stores work the same way. An employee at a check-out stand scans a bar code and sees all the information that is listed under that bar code.

There are similar tasks in the world of Java programming. For example, it’s often necessary to carry out the following tasks:

  • A user enters some number in the console and then the program has to read out the number which the user entered in the console.
  • A user enters some word in the console and then the program has to read out the word which the user entered in the console.

To carry out these tasks, Java uses the scanner. Remember: if something is entered in the console and you want to read what was entered, then you need to use the scanner.

We will examine several examples of code, after which you will:

  1. understand how the scanner works in practice. There are 6 examples of code in this article. We recommend that you run all of them on your computer and learn how they work in practice.
  2. master four scanner methods:

next ();

nextLine ();

nextInt ();

nextDouble ();

Methods are, roughly speaking, the actions that the Scanner can perform. In fact, there are many scanner methods. But at this stage, it will be sufficient to know just 4. Let’s get started!

Example No. 1 – The nextInt () method

Let’s suppose that we want the user to enter any integer from 1 to 10 in the console, and we want the program to display the number that the user entered.

Since we need to “scan” the number entered the user entered, we need to use the scanner. You can see the solution below, as well as comments on it.

Solution:

import java.util.Scanner;

class Test {

public static void main(String args[]){

System.out.print(«Enter any integer from 1 to 10: «);

Scanner scan = new Scanner(System.in);

int number = scan.nextInt();

System.out.println («You entered « + number);

}

}

If you run this code on your computer, you will see the following in the console:

Enter any integer from 1 to 10:

And if you enter, for example, the number 5, you will see the following in the console:

Enter any integer from 1 to 10: 5

You entered 5

Commentary:

In the article What is the Java Class library? we learned that Java has a huge library of tested code – ready-made frameworks for many problems that programmers face in their daily work. We also talked about various packages, classes, and methods. So, now we are going to work with the java.util package. This package includes the Scanner class, which has methods (actions) which allow us to work with the input and output of information in the console.

scanner_vertex-academy_en

In order to be able to use the Scanner class, we first need to take 3 steps.

Step No. 1 – Write the following line in the code:

import java.util.Scanner;

Why did we write this line? It helped us import the Scanner class from the java.util package. If we had forgotten to write it, the scanner simply wouldn’t work. Also, take note of where we wrote the line.

Then we asked the user to enter any whole number (integer) from 1 to 10. To do this, we wrote:

System.out.print(«Enter any integer from 1 to 10: «);

Step No. 2 – Declare the scanner

Scanner scan = new Scanner(System.in);

Scanner2 Vertex Academy

  1. With the help of Scanner scan, we declared that the variable will be called “scan” and it will fall into the Scanner class. It’s necessary to write the word Scanner in front of the name of the variable. By the way, you can call it whatever you want; you don’t need to call it “scan.”
  2. Then we wrote = new Scanner (System.in);

When you get to the topic of classes, you will gain a greater understanding of this construction.

Step No. 3 – Read the number from the console

int number = scan.nextInt();

    1. With the help of int number, we declared the variable number of the int type. Why did we choose the int type for the variable? Because, according to the condition of the task, the user has to enter any integer from 1 to 10. And since we expect that the number entered by the user will be a whole number (an integer), we chose the int type for the variable «number.»
    2. = scan. nextInt ();  this method of the nextInt () scanner is responsible for reading out the whole number which the user entered in the console. With the help of scan.nextInt () we read the entered whole number from the console and assign it to the variable «number.»

That’s it. From now on, the variable «number» will have the number entered by the user. Hurray!

Then we needed to enter the number that the user entered in the console and we did it with the help of this line:

System.out.println («You entered « + number);


Example No. 2 – The nextInt () method

Ask the user to enter any two whole numbers (integers). After that, you need to display the sum of these two numbers in the console.

Solution:

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

Scanner k = new Scanner(System.in);

System.out.println («Enter any two integers: «);

int number1 = k.nextInt();

int number2 = k.nextInt();

System.out.print(number1 + number2);//it displays the sum of number1 + number2

}

}

If run this code on your computer, you will see the following in the console:

Enter any two integers:

And if you enter, for example, the numbers 2 and 3, you will see the following in the console:

Enter any two integers:

2

3

5

Commentary:

Again, it takes 3 steps to use the scanner.

Step No. 1 – Import the scanner from the java.util package:

import java.util.Scanner;

Then we asked the user to enter two any integers:

System.out.println («Enter two any integers: «);

Step No. 2 – Declare the scanner

Scanner k = new Scanner(System.in);

  1. With the help of Scanner k, we declared that the variable will be called “k” and will fall into the «Scanner» class. It’s necessary to write the word «Scanner» in front of the name of the variable. By the way, you can call it whatever you want; you don’t need to call it “k.”
  2. Then we wrote = new Scanner (System.in);

Step No. 3 – Read out the number from the console

Actually, we did this two times, because we asked the user to enter two different numbers:

int number1 = k.nextInt();

int number2 = k.nextInt();

That’s it. From now on, the variables «number1» and «number2» will have the two numbers that the user entered.

And then we displayed the sum of «number1» and «number2»:

System.out.print(number1 + number2);//it displays the sum of number1 + number2


Example No. 3 – The nextLine () method

Let’s suppose that we want the user to enter any word or phrase in the console and we want the program to display the word or phrase the user entered.

Solution:

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println(«Enter any word or phrase: «);

String phrase1 = sc.nextLine();

System.out.println(phrase1);

}

}

If you run this code on your computer, you will see the following in the console:

Enter any word or phrase:

And if the user enters “I’m the Lord of the Scanner”, you will see the following in the console:

Enter any word or phrase:

I’m the Lord of the Scanner

I’m the Lord of the Scanner

Commentary:

Again, it takes 3 steps to use the scanner.

Step No. 1 – Import the scanner from the java.util package:

import java.util.Scanner;

Then we asked the user to enter any word or phrase:

System.out.println(«Enter any word or phrase: «);

Step No. 2 – Declare the scanner

Scanner sc = new Scanner(System.in);

Step No. 3 – Read out the word or phrase from the console

String phrase1 = sc.nextLine();

  1. With the help of String phrase1 we assigned the variable c of the String type the name «phrase1.» Why did we choose the String type for the variable? Because, according to the condition of the task, the user needs to enter any word or phrase. Since we expect the user to enter a word or phrase, we chose the String type for the variable phrase1.
  2. = sc. nextLine (); is responsible for reading out the word or phrase which the user entered in the console. With the help of the nextLine () method, we read out the entered word or phrase from the console and assign it to the variable phrase1.

From now on, the variable «phrase1» will have the phrase or word entered by the user.

Note: In examples 1 and 2, we used the nextInt (); method for whole numbers. In this example, we expected the user to enter a phrase or word (instead of whole numbers), so we used the nextLine (); method.

Then we displayed the word or phrase which the user entered in the console:

System.out.println(phrase1);


Example No. 4 – The nextLine () method

Let’s suppose that we want the user to enter several words or phrases at the same time and we want the program to display them in the one line.

Solution:

import java.util.Scanner;

public class Test {

 public static void main(String[] args) {

     Scanner sc = new Scanner(System.in);

     System.out.println(«Enter any two words or phrases: «);

     String phrase1 = sc.nextLine();

     String phrase2 = sc.nextLine();

     System.out.println(phrase1 + » « + phrase2);

 }

}

If you run this code on your computer, you will see the following in the console:

Enter any two words or phrases:

And if the user enters the phrase “I love” and then the word “Java”, you will see the following in the console:

I love

Java

I love Java

Commentary:

Again, it takes 3 steps to be able to use the scanner.

Step No. 1 – Import the scanner from the java.util package

import java.util.Scanner;

Then we asked the user to enter any two words or phrases:

System.out.println(«Enter any two words or phrases: «);

Step No. 2 – Declare the scanner

Scanner sc = new Scanner(System.in);

Step No. 3 – Read out the word or phrase from the console

String phrase1 = sc.nextLine();

String phrase2 = sc.nextLine();

    1. With the help of String phrase1 and String phrase2, we declared the variables phrase1 and phrase2 of the String type. Why did we choose the String type for the variable? Because, according to the condition of the task, the user needs to enter any two words or phrases. So we expect that the user will enter two words or phrases. And that’s why we chose the String type for the variables phrase1 and phrase2.
    2. = sc. nextLine (); is responsible for reading out the words or phrases from the console. With the help of the nextLine () method, we read out the entered word or phrase from the console and assign it to the variables phrase1 and phrase2.

Then we displayed the 2 words or phrases entered by the user:

System.out.println(phrase1 + » « + phrase2);

Note: We added “ “ between phrase1 and phrase2. If we hadn’t done this, we would see the following in the console:

I love

Java

I loveJava


Example No. 5 – The next () method

Let’s suppose that we want the user to enter any word or phrase and we want the program to display everything in the console up to the first space.

For example, if the user enters “Working with the scanner is cool”, then the program will only read out the word “Working”, because the first space appears after this word.

Or if, for example, the user enters “I love Java”, then the program will only read out the word “I”, because the first space appears after this word.

Anyway, you got the idea. Let’s take a look at the code.

Solution:

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println(«Enter any word of phrase: «);

String phrase1 = sc.next();

System.out.println(phrase1);

}

}

If you run this code on your computer, you will see the following in the console:

Enter any word or phrase:

And if the user enters “I’m the Lord of the Scanner”, you will see the following in the console:

Enter any word or phrase:

I’m the Lord of the Scanner

I’m

Commentary:

Again, it takes 3 steps to be able to use the scanner.

Step No. 1 – Import the scanner
from the java.util package:

import java.util.Scanner;

Step No. 2 – Declare the scanner

Scanner sc = new Scanner(System.in);

Then we asked the user to enter any word or phrase:

System.out.println(«Enter any word of phrase: «);

Step No. 3 – Read out the word or phrase from the console

String phrase1 = sc.next();

    1. With the help of String phrase1, we declared the variable c of the String type and named it phrase1. Why did we choose the String type for the variable? Because, according to the condition of the problem, the user needs to enter a word or a phrase. Since we expect the user to enter a word or a phrase, we chose the String type for variable phrase1.
    2. = sc. next (); is responsible for reading out the word or phrase up to the first space in the console. With the help of the next () method, we read out the entered word or phrase which appeared up to the first space from the console and assign it to variable phrase1.

From now on, variable phrase1 will have everything up to the first space.

Then we displayed everything up to the first space in the console:

System.out.println(phrase1);


Example No. 6 – The nextDouble () method

Let’s suppose you want the user to enter any fraction and for the program to read out the number the user entered and then display it in the console.

Solution:

import java.util.Scanner;

class Test {

public static void main(String args[]){

System.out.print(«Enter any fraction: «);

Scanner scan = new Scanner(System.in);

double number = scan.nextDouble();

System.out.println («You entered « + number);

}

}

If you run this code on your computer, you will see the following in the console:

Enter any fraction:

And if you enter the number 2,0 you will see the following in the console:

Enter any fraction:

2,0

You entered 2.0

Commentary:

Bug Vertex Academy

WARNING: BUG!!!

Note that in the code, all numbers of the «double» type are always written in the format “2.0”, i.e. separated by a point instead of comma.

And we intentionally entered the number of the double type in the format “2,0” – with the comma. Then the program displayed the number in the correct format: “2.0” – “You entered the number 2.0”

This is a bug. You just need to remember that when you enter the number of the double type in the console, you need to write it separated by the comma. If you enter the number in the console (not in the code) in the format “2.0”, the program will give you an error code!

Again, it takes 3 steps to use the scanner.

Step No. 1 – Import the scanner from the java.util package

import java.util.Scanner;

Then we asked the user to enter any fraction:

System.out.print(«Enter any fraction: «);

Step No. 2 – Declare the scanner

Scanner scan = new Scanner(System.in);

Step No. 3 — Read out the number from the console

double number = scan.nextDouble();

    1. With the help of double number, we declared the variable number of the double type. Why did we choose the double type for the variable? Because according to the condition of the problem, the user needs to enter any fraction. So we expect the user to enter any fraction. That’s why we chose the double type for the variable number.
    2. = sc. nextDouble (); the method of the nextDouble() scanner is responsible for reading out the fraction which the user entered in the console. i.e. with the help of the scan.nextDouble () method, we read out the entered fraction from the console and assign it to the variable «number.»

That’s it. From now on, the variable «number» will have the number entered by the user.

Then we needed to display the number entered by the user in the console, and we did it with the help of:

System.out.println («You entered « + number);


LET’S SUMMARIZE

In order to use the scanner, you need to take 3 steps:

Step No. 1 — Import the scanner from the java.util package

import java.util.Scanner;

Step No. 2 – Declare the scanner. For example:

Scanner scan = new Scanner(System.in);

Step No. 3 – Set the appropriate method for reading out from the console. For example:

int number = scan.nextInt();

Scanner methods that you already know:

next (); — reads the entered line up to the first space

nextLine (); — reads the whole entered line

nextInt (); — reads the entered number of the int type

nextDouble (); — reads the entered number of the double type

Keep in mind that if you use the nextDouble () methods for fractions, you need to write the numbers separated by a comma, instead of period. For example: 7,5

You can find more articles in our Java Tutorial for Beginners. 

In file handling reading files based on the character is asked frequently in core java interviews. The following program is how to read files based on a character by character and displaying the result.

Step 1: Creating an object to FileReader and BufferedReader.

Step 2: Reading and displaying the file charcater by character.

while((c = br.read()) != -1)

{

char character = (char) c;

System.out.println(character);

}

FileReadByChar.java

package File;

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

public class FileReadByChar 
{
   public static void main(String[] args) throws IOException 
   {
      File f=new File("input.txt");     //Creation of File Descriptor for input file
      FileReader fr=new FileReader(f);   //Creation of File Reader object
      BufferedReader br=new BufferedReader(fr);  //Creation of BufferedReader object
      int c = 0;             
      while((c = br.read()) != -1)         //Read char by Char
      {
            char character = (char) c;          //converting integer to char
            System.out.println(character);        //Display the Character
      }
      
   }
}

Output:

W
e
l
c
o
m
e
 
t
o
 
C
a
n
d
i
d
 
J
a
v
a
 
S
e
s
s
i
o
n




F
i
r
s
t
 
S
e
s
s
i
o
n
 
i
s
 
C
o
r
e
 
J
a
v
a


L
e
a
r
n
i
n
g
 
j
a
v
a
 
i
s
 
i
n
t
e
r
e
s
t
i
n
g

Понравилась статья? Поделить с друзьями:
  • Read mode in word
  • Read longest english word
  • Read jessica s letter and choose the correct word
  • Read it again and cross out the wrong word according to james
  • Read harrys postcard to peter complete with one word