×

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 Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.