Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.io.StringWriter class in Java
Next article icon

Java.io.StringReader class in Java

Last Updated : 12 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

StringReader class in Java is a character stream class whose source is a string. It inherits Reader Class. Closing the StringReader is not necessary, it is because system resources like network sockets and files are not used. Let us check more points about StringReader Class in Java.

Declare StringReader Class in Java

public class StringReader extends Reader  

Constructor in Java StringReader Class

The constructor used with StringReader Class in Java is mentioned below:

StringReader(String s) : Creates a new string reader.

Methods in Java StringReader Class

Methods in StringReader Class in Java are mentioned below:

Method Description
int read() Reads a single character
int read(char[] cbuf, int off, int len)               Reads characters into a portion of an array
boolean ready() Tells whether this stream is ready to be read
boolean markSupported() Tells whether stream support mark
void mark(int readAheadLimit) Marks the mark present in the position present in the stream
void reset() Resets the stream to the most recent mark, or to the beginning of the string if it has never been marked.
long skip(long ns) Resets specified number of characters in a stream
void close() Closes the stream

1. int read()

Reads a single character.

Syntax :public int read() throws IOException    Returns:  The character read, or -1 if the end of the stream has been reached    Throws:  IOException

2. int read(char[] cbuf, int off, int len)

Reads characters into a portion of an array.

Syntax :public int read(char[] cbuf,int off, int len)           throws IOException    Parameters:  cbuf - Destination buffer  off - Offset at which to start writing characters  len - Maximum number of characters to read    Returns:  The number of characters read, or -1 if the end of the stream has been reached  Throws:  IOException

3. boolean ready()

Tells whether this stream is ready to be read.

Syntax :public boolean ready()                throws IOException    Returns:  True if the next read() is guaranteed not to block for input    Throws:  IOException

4. boolean markSupported()

Tells whether this stream supports the mark() operation, which it does.

Syntax :public boolean markSupported()    Returns:  true if and only if this stream supports the mark operation.

5. void mark(int readAheadLimit)

Marks the present position in the stream. Subsequent calls to reset() will reposition the stream to this point.

Syntax :public void mark(int readAheadLimit)            throws IOException    Parameters:  readAheadLimit - Limit on the number of characters that may   be read while still preserving the mark. Because the stream's input   comes from a string, there is no actual limit, so this argument   must not be negative, but is otherwise ignored.    Throws:  IllegalArgumentException  IOException

6. void reset()

Resets the stream to the most recent mark, or to the beginning of the string if it has never been marked.

Syntax :public void reset()             throws IOException    Throws:  IOException 

7. long skip(long ns)

It Skips the specified number of characters in the stream. Returns the number of characters that were skipped. The ns parameter may be negative, even though the skip method of the Reader superclass throws an exception in this case. Negative values of ns cause the stream to skip backwards. Negative return values indicate a skip backwards. It is not possible to skip backwards past the beginning of the string. If the entire string has been read or skipped, then this method has no effect and always returns 0.

Syntax :public long skip(long ns)            throws IOException    Parameters:  ns - The number of characters to skip    Returns:  The number of characters actually skipped    Throws:  IOException

8. void close()

Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), or reset() invocations will throw an IOException. Closing a previously closed stream has no effect.

Syntax :public void close()

Example

Java




// Java program demonstrating StringReader methods
import java.io.IOException;
import java.io.StringReader;
  
// Driver class
class StringReaderDemo {
    // main function
    public static void main(String[] args)
        throws IOException
    {
        StringReader str = new StringReader(
            " GeeksforGeeks & quot;);
        char c[] = new char[7];
  
        // illustrating markSupported()
        if (str.markSupported()) {
            System.out.println(
                " Mark method is supported & quot;);
            // illustrating mark()
            str.mark(100);
        }
  
        // illustrating skip() method
        str.skip(5);
  
        // whether this stream is ready to be read.
        if (str.ready()) {
            // illustrating read() method
            System.out.print((char)str.read());
  
            // illustrating read(char cff[],int off,int len)
            str.read(c);
            for (int i = 0; i & lt; 7; i++) {
                System.out.print(c[i]);
            }
        }
  
        // illustrating reset() method
        str.reset();
  
        for (int i = 0; i & lt; 5; i++) {
            System.out.print((char)str.read());
        }
  
        // illustrating close()
        str.close();
    }
}
 
 

Output

Mark method is supported  forGeeksGeeks


Next Article
Java.io.StringWriter class in Java

N

Nishant Sharma
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • Java.io.StringWriter class in Java
    Java StringWriter class creates a string from the characters of the String Buffer stream. Methods of the StringWriter class in Java can also be called after closing the Stream as this will raise no IO Exception. Declaration in Java StringWriter Classpublic class StringWriter extends WriterConstructo
    6 min read
  • Java.io.Writer class in Java
    This abstract class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.
    4 min read
  • Java.io.LineNumberReader class in Java
    A buffered character-input stream that keeps track of line numbers. This class defines methods setLineNumber(int) and getLineNumber() for setting and getting the current line number respectively. By default, line numbering begins at 0. This number increments at every line terminator as the data is r
    4 min read
  • Java.io.Printstream Class in Java | Set 2
    Java.io.Printstream Class in Java | Set 1More Methods: PrintStream printf(Locale l, String format, Object... args) : A convenience method to write a formatted string to this output stream using the specified format string and arguments. Syntax :public PrintStream printf(Locale l, String format, Obje
    6 min read
  • Java.io.Printstream Class in Java | Set 1
    A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the c
    5 min read
  • Java.io.PrintWriter class in Java | Set 1
    Java PrintWriter class gives Prints formatted representations of objects to a text-output stream. It implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams. Unlike the PrintStream class, if au
    5 min read
  • Java.io.PrintWriter class in Java | Set 2
    Java.io.PrintWriter class in Java | Set 1 More methods: PrintWriter printf(Locale l, String format, Object... args) : A convenience method to write a formatted string to this writer using the specified format string and arguments. Syntax :public PrintWriter printf(Locale l, String format, Object...
    7 min read
  • Java.io.StreamTokenizer Class in Java | Set 1
    Java.io.StreamTokenizer class parses input stream into "tokens".It allows to read one token at a time. Stream Tokenizer can recognize numbers, quoted strings, and various comment styles. Declaration : public class StreamTokenizer extends Object Constructor : StreamTokenizer(Reader arg) : Creates a t
    9 min read
  • Java.io.PushbackInputStream class in Java
    Pushback is used on an input stream to allow a byte to be read and then returned (i.e, "pushed back") to the stream. The PushbackInputStream class implements this idea. It provides a mechanism "peek" at what is coming from an input stream without disrupting it. It extends FilterInputStream.Fields: p
    7 min read
  • Java.io.StreamTokenizer Class in Java | Set 2
    StringTokenizer Class in Java | Set 1 Methods: parseNumbers() : java.io.StreamTokenizer.parseNumbers() specifies that the number in StreamTokenizer is parsed, so that each character - " 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 " has a numeric attribute. When the parser encounters a word token that has the forma
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences