×

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream.

Program to read string using Buffer reader

import java.io.*;
class  Demo
{
  public static void main(String s[])
 {
    int a=1;    // Here “a” assigned to 1.
  System. out. println (“a = “+a);
}
}

Output

Buffer reader to read string

Explanation

The variable was assigned the value before running the above program. This way is called the static way.

In Java, to read inputs, there are 2 ways

1. Scanner Class

2. Buffer Reader

Buffered Reader

  • Using this class, we can read data from the input stream.
  • This class inherits the properties of the Reader class.

Syntax for object creation In Input Stream

Input Stream objectname = new FileInputStream();

Buffered Reader class Syntax

public class Buffered Reader extends Reader;

Constructors in Buffered Reader

  • Buffered Reader(Reader r): It is used to generate an Input stream by considering a default size.
  • Buffered Reader(Reader r, int size): It generates an Input stream with the exact size, passed as a parameter.

Methods in Buffered Reader class

  • read ()
  • close ()
  • read (char[] c, int start, int length)
  • ready ()
  • mark ()
  • reset ()
  • mark supported ()

read() method

  • It is used to read single characters from the stream.
  • It returns -1 if it reaches the end of the input.
  • It represents whether the next character is present or not.
  • The return type of the read() method is int(Integer).

Syntax:

public int read()

   Program

import java.io.*;
public class Main
{
public static void main(String[] args)  throws IOException 
{
Buffered Reader object2 = new BufferedReader(new InputStreamReader(System.in));
    System. out. println("enter the string");
    char s1 = object2.read();
    System. out. println(s1);
}
}

Output

Buffer reader to read string

readLine() method

  • It is used to read the entire line of the input.

Program

import java.io.*;
public class Main
{
public static void main(String[] args)  throws IOException 
{    
BufferedReader object2 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the string");
    String s1 = object2.readLine();
    System.out.println("The string is");
    System.out.println(s1);
}
}

  Output

Buffer reader to read string

close () method

  • Close method is used to close the character stream.
  • If the stream has been closed, performing methods like reading (), readLine and other methods throw an IOException.

read(char[] c, int start, int length)

  • It stores the reading characters in the array form.
  • It returns the count of characters.

Syntax:

public int read(char[] c, int start, int length)

skip (long s) method

 This method returns the input that matches the specified pattern, ignoring delimiters.

Syntax:

public long skip(String s)

Program

import java.util.*;  
import java.util.regex.Pattern;  
class Main {    
   public static void main(String args[]){   
        Scanner scan = new Scanner("Hello! Everyone");  
        scan.skip(Pattern.compile("..llo"));  
        System.out.println("Remaining  Stringi s: " +scan.nextLine());  
        scan.close();  
          }  
}  

Output:

Buffer reader to read string

ready() method

  • It checks whether the input stream is ready to be read.
  • Return ready() method is boolean.

Syntax:

public boolean ready();

Program

import java.io.*;
import java.util.*;
class Main {
    public static void main(String[] args)
    {
  
        try {
  
            String str = "Java Language";
            // create reader instance
            Reader reader= new StringReader(str);  
      
      
            System.out.println("Is Reader ready "+ "to be read: "+ reader.ready());
            // check whether it is ready or not
            reader.close();
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output

Buffer reader to read string

mark(int Limit)

  • This method is used to represent the present position in the stream.
  • Void is the return type.

Syntax:

public void mark(int Limit)

Program:

import java.io.*;  
class Example17{  
  public static void main(String[] s) throws IOException{  
object1 = new FileInputStream(“Fruit.txt”);
   BufferedReader b = new BufferedReader(new InputStreamReader(object1));
    b . mark(1);  
    System . out . println(b.read());
     b . close();  
    
  }  
} 

  Output

Buffer reader to read string

In the fruits file, we have content as Apple.

reset ()

  • It is used to reset the stream.
  • Void is the return type.

Program

import java.lang.*;
import java.util.concurrent.atomic.DoubleAdder;
  
public class Main {
    public static void main(String args[])
    {
        DoubleAdder number = new DoubleAdder();
  
        number.add(3);
  
        // reset operation on variable number
        number.reset();
  
        // Print after add operation
        System.out.println(" the current value is: " + number);
    }
}

Output:

Buffer reader to read string

mark supported () method

  • It is used to check whether it supports the mark() method.
  • void is the return type.

Syntax:

 public void markSupported()

Program

import java.io.ByteArrayInputStream;  
import java.io.IOException;  
public class Main {  
    public static void main(String[] args) throws IOException {  
        byte[] b = {1,2,3,4,5};  
        ByteArrayInputStream ba = null;  
        ba = new ByteArrayInputStream(b);  
        boolean isMarkSupported = ba.markSupported();  
        System.out.println("Is mark supported : "+isMarkSupported);  
        
    }  
}  

Output

Buffer reader to read string

Related Topics

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.