CharBuffer append() métodos en Java con ejemplos

agregar (carácter c)

El método append(char c) de java.nio.CharBuffer Class se usa para agregar el carácter especificado a este búfer (operación opcional). 
Una invocación de este método de la forma dst.append(c) se comporta exactamente de la misma manera que la invocación 
dst.put(c) 
Sintaxis: 

public CharBuffer append(char c)

Parámetros: este método toma el carácter de 16 bits para agregar.
Valor devuelto: este método devuelve este búfer, en el que se inserta el valor de char.
Excepción: este método arroja las siguientes excepciones: 

  • BufferOverflowException: si no hay espacio suficiente en este búfer
  • ReadOnlyBufferException : si este búfer es de solo lectura

A continuación se muestran los ejemplos para ilustrar el método append(char c):
Ejemplo 1:

Java

// Java program to demonstrate
// append() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the CharBuffer
        int capacity = 3;
 
        // Creating the CharBuffer
        try {
 
            // creating object of CharBuffer
            // and allocating size capacity
            CharBuffer charbuffer
                = CharBuffer.allocate(capacity);
 
            // append the value in CharBuffer
            // using append() method
            charbuffer.append('a')
                .append('b')
                .append('c')
                .rewind();
 
            // print the CharBuffer
            System.out.println("Original CharBuffer:  "
                               + Arrays.toString(
                                     charbuffer.array()));
        }
 
        catch (BufferOverflowException e) {
 
            System.out.println("Exception throws : " + e);
        }
 
        catch (ReadOnlyBufferException e) {
 
            System.out.println("Exception throws : " + e);
        }
    }
}
Producción: 

Original CharBuffer:  [a, b, c]

 

Ejemplo 2: Para demostrar BufferOverflowException.

Java

// Java program to demonstrate
// append() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the CharBuffer
        int capacity = 3;
 
        // Creating the CharBuffer
        try {
 
            // creating object of CharBuffer
            // and allocating size capacity
            CharBuffer charbuffer
                = CharBuffer.allocate(capacity);
 
            // append the value in CharBuffer
            // using append() method
            charbuffer.append('a')
                .append('b')
                .append('c');
 
            // print the CharBuffer
            System.out.println("Original CharBuffer:  "
                               + Arrays.toString(
                                     charbuffer.array()));
 
            // again appending the value in CharBuffer
            // using append() method
            System.out.println("\nBuffer position : "
                               + charbuffer.position());
            charbuffer.append('x');
        }
 
        catch (BufferOverflowException e) {
 
            System.out.println("buffer's current position "
                               + "is not smaller than its limit");
            System.out.println("Exception throws : " + e);
        }
 
        catch (ReadOnlyBufferException e) {
 
            System.out.println("Exception throws : " + e);
        }
    }
}
Producción: 

Original CharBuffer:  [a, b, c]

Buffer position : 3
buffer's current position is not smaller than its limit
Exception throws : java.nio.BufferOverflowException

 

Ejemplos 3: Para demostrar ReadOnlyBufferException.

Java

// Java program to demonstrate
// append() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the CharBuffer
        int capacity = 3;
 
        // Creating the CharBuffer
        try {
 
            // creating object of CharBuffer
            // and allocating size capacity
            CharBuffer charbuffer
                = CharBuffer.allocate(capacity);
 
            // append the value in CharBuffer
            // using append() method
            charbuffer.append('a')
                .append('b')
                .append('c');
 
            // print the CharBuffer
            System.out.println("Original CharBuffer:  "
                               + Arrays.toString(
                                     charbuffer.array()));
 
            // Creating a read-only copy of CharBufferBuffer
            // using asReadOnlyBuffer() method
            CharBuffer chb = charbuffer.asReadOnlyBuffer();
 
            System.out.println("\nTrying to append the char value"
                               + " in read-only buffer");
 
            // putting the value in readonly CharBuffer
            // using append() method
            chb.append('d');
        }
 
        catch (BufferOverflowException e) {
 
            System.out.println("buffer's current position "
                               + "is not smaller than its limit");
            System.out.println("Exception throws : " + e);
        }
 
        catch (ReadOnlyBufferException e) {
 
            System.out.println("Exception throws : " + e);
        }
    }
}
Producción: 

Original CharBuffer:  [a, b, c]

Trying to append the char value in read-only buffer
Exception throws : java.nio.ReadOnlyBufferException

 

Referencia: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#append-char-
 

agregar (CharSequence csq)

El método append(CharSequence csq) de java.nio.CharBuffer Class se usa para agregar la secuencia de caracteres especificada a este búfer (operación opcional). 
Según la especificación de toString para la secuencia de caracteres csq, es posible que no se agregue la secuencia completa. Por ejemplo, invocar el método toString de un búfer de caracteres devolverá una subsecuencia cuyo contenido depende de la posición y el límite del búfer.
Sintaxis: 
 

public CharBuffer append(CharSequence csq)

Parámetros: este método toma la secuencia de caracteres para agregar. Si csq es nulo, los cuatro caracteres «nulo» se agregan a este búfer de caracteres.
Valor devuelto: este método devuelve este búfer.
Excepción: este método arroja la siguiente excepción: 
 

  • BufferOverflowException: si no hay espacio suficiente en este búfer
  • ReadOnlyBufferException : si este búfer es de solo lectura

A continuación se muestran los ejemplos para ilustrar el método append(CharSequence csq):
Ejemplo 1:
 

Java

// Java program to demonstrate
// append() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the CharBuffer
        int capacity = 3;
 
        // Declaring and initializing CharSequence
        CharSequence cha = "cow";
 
        // Creating the CharBuffer
        try {
 
            // creating object of CharBuffer
            // and allocating size capacity
            CharBuffer charbuffer
                = CharBuffer.allocate(capacity);
 
            // appending the CharSequence in CharBuffer
            // using append() method
            charbuffer.append(cha)
                .rewind();
 
            // print the CharBuffer
            System.out.println("Original CharBuffer:  "
                               + Arrays.toString(
                                     charbuffer.array()));
        }
 
        catch (BufferOverflowException e) {
 
            System.out.println("Exception throws : " + e);
        }
 
        catch (ReadOnlyBufferException e) {
 
            System.out.println("Exception throws : " + e);
        }
    }
}
Producción: 

Original CharBuffer:  

 

Ejemplo 2: Para demostrar BufferOverflowException.
 

Java

// Java program to demonstrate
// append() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the CharBuffer
        int capacity = 2;
 
        // Declaring and initializing CharSequence
        CharSequence cha = "cow";
 
        // Creating the CharBuffer
        try {
 
            // creating object of CharBuffer
            // and allocating size capacity
            CharBuffer charbuffer
                = CharBuffer.allocate(capacity);
 
            // appending the CharSequence in CharBuffer
            // using append() method
            charbuffer.append(cha)
                .rewind();
 
            // print the CharBuffer
            System.out.println("Original CharBuffer:  "
                               + Arrays.toString(
                                     charbuffer.array()));
        }
 
        catch (BufferOverflowException e) {
            System.out.println("CharSequence length is greater"
                               + " than the length of charbuffer");
            System.out.println("Exception throws : " + e);
        }
 
        catch (ReadOnlyBufferException e) {
 
            System.out.println("Exception throws : " + e);
        }
    }
}
Producción: 

CharSequence length is greater than the length of charbuffer
Exception throws : java.nio.BufferOverflowException

 

Ejemplo 3: Para demostrar ReadOnlyBufferException.
 

Java

// Java program to demonstrate
// append() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the CharBuffer
        int capacity = 2;
 
        // Declaring and initializing CharSequence
        CharSequence cha = "cow";
 
        // Creating the CharBuffer
        try {
 
            // creating object of CharBuffer
            // and allocating size capacity
            CharBuffer charbuffer
                = CharBuffer.allocate(capacity);
 
            // Creating a read-only copy of CharBuffer
            // using asReadOnlyBuffer() method
            CharBuffer charbuffer1
                = charbuffer.asReadOnlyBuffer();
 
            // appending the CharSequence in CharBuffer
            // using append() method
            charbuffer1.append(cha)
                .rewind();
 
            // print the CharBuffer
            System.out.println("Original CharBuffer:  "
                               + Arrays.toString(
                                     charbuffer1.array()));
        }
 
        catch (BufferOverflowException e) {
            System.out.println("CharSequence length is greater"
                               + " than the length of charbuffer");
            System.out.println("Exception throws : " + e);
        }
 
        catch (ReadOnlyBufferException e) {
            System.out.println("Trying to append CharSequence "
                               + "in read-only charbuffer");
            System.out.println("Exception throws : " + e);
        }
    }
}
Producción: 

Trying to append CharSequence in read-only charbuffer
Exception throws : java.nio.ReadOnlyBufferException

 

Referencia: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#append-java.lang.CharSequence-

Publicación traducida automáticamente

Artículo escrito por RohitPrasad3 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *