×

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

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.