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:
Reader read(CharBuffer) method in Java with Examples
Next article icon

CharBuffer read() methods in Java with Examples

Last Updated : 28 Jul, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

The read() method of java.nio.CharBuffer Class is used to read characters into the specified character buffer. The buffer is used as a repository of characters as-is: the only changes made are the results of a put operation. No flipping or rewinding of the buffer is performed.

Syntax:

public int read(CharBuffer target)

Parameter: This method takes the buffer to read characters into.

Return Value: This method returns the number of characters added to the buffer, or -1 if this source of characters is at its end.

Exception: This method throws following exception:-

  • IOException – if an I/O error occurs
  • NullPointerException – if target is null
  • ReadOnlyBufferException – if target is a read only buffer

Below are the examples to illustrate the read() method:

Examples 1:




// Java program to demonstrate
// read() method
  
import java.nio.*;
import java.util.*;
import java.io.IOException;
  
public class GFG {
    public static void main(String[] args)
    {
        try {
  
            // Declare and initialize the char array
            char[] cb1 = { 'x', 'y', 'z' };
            char[] cb2 = { 'a', 'b', 'c', 'd', 'e' };
  
            // wrap the char array into CharBuffer
            // using wrap() method
            CharBuffer charBuffer1
                = CharBuffer.wrap(cb1);
  
            // wrap the char array into CharBuffer
            // using wrap() method
            CharBuffer charBuffer2
                = CharBuffer.wrap(cb2);
  
            // print the byte buffer
            System.out.println("CharBuffer Before operation is: "
                               + Arrays.toString(
                                     charBuffer1.array())
                               + "\nTarget Charbuffer: "
                               + Arrays.toString(
                                     charBuffer2.array()));
  
            // Get the value of the number of Character
            // read from the charBuffer
            // using read() method
            int value
                = charBuffer1
                      .read(charBuffer2);
  
            // print the byte buffer
            System.out.println("\nCharBuffer After operation is: "
                               + Arrays.toString(
                                     charBuffer1.array())
                               + "\nTarget Charbuffer: "
                               + Arrays.toString(
                                     charBuffer2.array())
                               + "\nno of value changed: "
                               + value);
        }
        catch (IOException e) {
            System.out.println("an I/O error occurs");
            System.out.println("Exception throws: " + e);
        }
        catch (NullPointerException e) {
            System.out.println("target charbuffer is null");
            System.out.println("Exception throws: " + e);
        }
        catch (ReadOnlyBufferException e) {
            System.out.println("target is a read only buffer");
            System.out.println("Exception throws: " + e);
        }
    }
}
 
 
Output:
  CharBuffer Before operation is: [x, y, z]  Target Charbuffer: [a, b, c, d, e]    CharBuffer After operation is: [x, y, z]  Target Charbuffer: [x, y, z, d, e]  no of value changed: 3  

Examples 2: For NullPointerException




// Java program to demonstrate
// read() method
  
import java.nio.*;
import java.util.*;
import java.io.IOException;
  
public class GFG {
    public static void main(String[] args)
    {
        try {
  
            // Declare and initialize the char array
            char[] cb1 = { 'x', 'y', 'z' };
  
            // wrap the char array into CharBuffer
            // using wrap() method
            CharBuffer charBuffer1
                = CharBuffer.wrap(cb1);
  
            // print the byte buffer
            System.out.println("CharBuffer Before operation is: "
                               + Arrays.toString(
                                     charBuffer1.array()));
  
            // Get the value of number of Character
            // read from the charBuffer
            // using read() method
            int value = charBuffer1.read(null);
        }
  
        catch (IOException e) {
            System.out.println("\nan I/O error occurs");
            System.out.println("Exception throws: " + e);
        }
  
        catch (NullPointerException e) {
            System.out.println("\ntarget charbuffer is null");
            System.out.println("Exception throws: " + e);
        }
  
        catch (ReadOnlyBufferException e) {
            System.out.println("\ntarget is a read only buffer");
            System.out.println("Exception throws: " + e);
        }
    }
}
 
 
Output:
  CharBuffer Before operation is: [x, y, z]    target charbuffer is null  Exception throws: java.lang.NullPointerException  

Examples 3: For ReadOnlyBufferException




// Java program to demonstrate
// read() method
  
import java.nio.*;
import java.util.*;
import java.io.IOException;
  
public class GFG {
    public static void main(String[] args)
    {
        try {
  
            // Declare and initialize the char array
            char[] cb1 = { 'x', 'y', 'z' };
            char[] cb2 = { 'a', 'b', 'c', 'd', 'e' };
  
            // wrap the char array into CharBuffer
            // using wrap() method
            CharBuffer charBuffer1
                = CharBuffer.wrap(cb1);
  
            // wrap the char array into CharBuffer
            // using wrap() method
            CharBuffer charBuffer2
                = CharBuffer.wrap(cb2);
  
            // print the byte buffer
            System.out.println("CharBuffer Before operation is: "
                               + Arrays.toString(
                                     charBuffer1.array())
                               + "\nTarget Charbuffer: "
                               + Arrays.toString(
                                     charBuffer2.array()));
  
            // converting Charbuffer to readonlybuff
            CharBuffer readonlybuff
                = charBuffer2.asReadOnlyBuffer();
  
            // Get the value of number of Character
            // read from the charBuffer
            // using read() method
            int value = charBuffer1.read(readonlybuff);
  
            // print the byte buffer
            System.out.println("\nCharBuffer After operation is: "
                               + Arrays.toString(
                                     charBuffer1.array())
                               + "\nTarget Charbuffer: "
                               + Arrays.toString(
                                     charBuffer2.array())
                               + "\nno of value changed: "
                               + value);
        }
        catch (IOException e) {
            System.out.println("\nan I/O error occurs");
            System.out.println("Exception throws: " + e);
        }
        catch (NullPointerException e) {
            System.out.println("\ntarget charbuffer is null");
            System.out.println("Exception throws: " + e);
        }
        catch (ReadOnlyBufferException e) {
            System.out.println("\ntarget is a read only buffer");
            System.out.println("Exception throws: " + e);
        }
    }
}
 
 
Output:
  CharBuffer Before operation is: [x, y, z]  Target Charbuffer: [a, b, c, d, e]    target is a read only buffer  Exception throws: java.nio.ReadOnlyBufferException  

Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#read-java.nio.CharBuffer-



Next Article
Reader read(CharBuffer) method in Java with Examples

R

RohitPrasad3
Improve
Article Tags :
  • Java
  • Java-CharBuffer
  • Java-Functions
  • Java-NIO package
Practice Tags :
  • Java

Similar Reads

  • CharBuffer rewind() methods in Java with Examples
    The rewind() method of java.nio.CharBuffer Class is used to rewind this buffer. The position is set to zero and the mark is discarded. Invoke this method before a sequence of channel-write or get operations, assuming that the limit has already been set appropriately. Invoking this method neither cha
    2 min read
  • CharBuffer order() methods in Java with Examples
    The order() method of java.nio.CharBuffer class is used to retrieve this buffer's byte order. The byte order of a char buffer created by allocation or by wrapping an existing char array is the native order of the underlying hardware. The byte order of a char buffer created as a view of a byte buffer
    2 min read
  • CharBuffer reset() methods in Java with Examples
    The reset() method of java.nio.CharBuffer Class is used to reset this buffer's position to the previously-marked position. Invoking this method neither changes nor discards the mark's value. Syntax: public final CharBuffer reset() Return Value: This method returns this buffer. Below are the examples
    2 min read
  • Reader read(CharBuffer) method in Java with Examples
    The read(CharBuffer) method of Reader Class in Java is used to read the specified characters into a CharBuffer instance. This method blocks the stream till: It has taken some input from the stream. Some IOException has occurred It has reached the end of the stream while reading. Syntax: public int r
    2 min read
  • Buffer rewind() methods in Java with Examples
    The rewind() method of java.nio.ByteBuffer Class is used to rewind this buffer. The position is set to zero and the mark is discarded. Invoke this method before a sequence of channel-write or get operations, assuming that the limit has already been set appropriately. Invoking this method neither cha
    2 min read
  • CharBuffer flip() methods in Java with Examples
    The flip() method of java.nio.CharBuffer Class is used to flip this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of
    2 min read
  • CharBuffer mark() methods in Java with Examples
    The mark() method of java.nio.CharBuffer Class is used to set this buffer's mark at its position. Syntax: public CharBuffer mark() Return Value: This method returns this buffer. Below are the examples to illustrate the mark() method: Examples 1: // Java program to demonstrate // mark() method import
    2 min read
  • CharBuffer chars() methods in Java with Examples
    The chars() method of java.nio.CharBuffer Class is used to return a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. The stream binds to this sequence when the terminal stream operation commences (specific
    2 min read
  • CharBuffer clear() methods in Java with Examples
    The clear() method of java.nio.CharBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. Invoke this method before using a sequence of channel-read or put operations to fill this buffer. For example: // Prepare buffer for
    2 min read
  • CharBuffer limit() methods in Java with Examples
    The limit() method of java.nio.CharBuffer Class is used to set this buffer's limit. If the position is larger than the new limit then it is set to the new limit. If the mark is defined and larger than the new limit then it is discarded. Syntax: public CharBuffer limit(int newLimit) Return Value: Thi
    2 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