Metodos Java
Metodos Java
System.out.println(cadena.endsWith("n")); //Nos
devuelve true
System.out.println(cadena.startsWith("e")); //Nos
devuelve false, Java distingue entre mayusculas y minusculas
System.out.println(cadena.replace('a', 'e')); //
Cambia todas las a por e
System.out.println(cadena.toLowerCase()); //Transforma
el String a minusculas
System.out.println(cadena.toUpperCase()); //Transforma
el String a mayusculas
}
Hola a todos, hoy os explicare los método mas utilizado de la clase
String.
La clase String tiene varios métodos muy útiles como saber su
longitud, trocear la cadena, etc. Recuerda que para invocar
un método debemos escribir el nombre del String, un punto y el
nombre del método, más sus parámetros. Es importante que si
necesitas almacenar el valor devuelto, uses una variable para ello.
Por ejemplo:
String cadena=”americano”;
boolean empiezaPor=cadena.startWith (“a”);
Estos son los métodos mas conocidos:
compareTo Sirve para comparar cadenas, devuelve un número según el resultado. Recuerda que no sigue el Un parámetro St
alfabeto español, lo compara según la tabla ASCII.
copyValueOf Crea un nuevo String a partir de un array de char. Este método debe invocarse de manera Un array de cha
estática, es decir, String.copyValueOf(array_char)
endsWith Indica si la cadena acaba con el String pasado por parámetro. String
getBytes Devuelve un array de bytes con el código ASCII de los caracteres que forman el String. Ningún parámet
indexOf Devuelve la posición en la cadena pasada por parámetro desde el principio. -1 si no existe. String o char
indexOf Igual que el anterior, pero ademas le indicamos la posición desde donde empezamos a buscar. String o char, el
lastIndexOf Devuelve la posición en la cadena pasada por parámetro desde el final. -1 si no existe. String o char
lastIndexOf Igual que el anterior, pero ademas le indicamos la posición desde donde empezamos a buscar. String o char, el
matches Indica si la cadena cumple con la expresión pasada como parámetro. Pincha aquí para tener mas String
detalles.
replace Devuelve un String cambiando los caracteres que nosotros le indiquemos. Dos parámetros
segundo por el q
replaceAll Devuelve un String intercambiando todas las coincidencias que se encuentren. Dos parametros
y el segundo por
startsWith Indica si la cadena empieza por una cadena pasada por parámetro. String
toCharArray Devuelve en un array de char, todos los caracteres de una String. Ningún parámet
valueOf Transforma una variable primitiva en un String. Para invocarse debe usarse con String. Por Un parámetro, q
ejemplo, String.valueOf(variable)
boolea
char
double
int
float
long
Array
Refere
Hola a todos, hoy os explicare a usar las funciones matemáticas
mas usadas de la clase Math de Java.
Esta clase ya viene incluida en nuevas versiones de Java, por lo
que no habrá que importar ningún paquete para ello.
Para utilizar esta clase, debemos
escribir Math.método(parámetros); donde método sera uno de
los siguientes y parámetros aquellos que tengamos que usar. Un
método puede estar sobrescrito para distintos tipos de datos.
Recuerda que si almacenas el resultado de la función, debe
coincidir con el tipo de la variable.
max Devuelve el mayor de dos entre dos valores. Dos parametros que pue
min Devuelve el menor de dos entre dos valores. Dos parametros que pue
random Devuelve un número aleatorio entre 0 y 1. Se pueden cambiar el rango de generación. Ninguno
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //crear un objeto Scanner
String nombre;
double radio;
int n;
System.out.print("Introduzca su nombre: ");
nombre = sc.nextLine(); //leer un String
System.out.println("Hola " + nombre + "!!!");
System.out.print("Introduzca el radio de la circunferencia: ");
radio = sc.nextDouble(); //leer un double
System.out.println("Longitud de la circunferencia: " + 2*Math.PI*radio);
System.out.print("Introduzca un número entero: ");
n = sc.nextInt(); //leer un entero
System.out.println("El cuadrado es: " + Math.pow(n,2));
}
}
Si introducimos la cadena:
12 20.001 Lucas w
12
20.001
Lucas
w
METODO DESCRIPCIÓN
nextXxx() Devuelve el siguiente token como un tipo básico. Xxx es el
tipo. Por ejemplo, nextInt() para leer un entero, nextDouble
para leer un double, etc.
next() Devuelve el siguiente token como un String.
nextLine() Devuelve la línea entera como un String. Elimina el final \n del
buffer
hasNext() Devuelve un boolean. Indica si existe o no un siguiente token
para leer.
hasNextXxx() Devuelve un boolean. Indica si existe o no un siguiente token
del tipo especificado en Xxx, por ejemplo hasNextDouble()
useDelimiter(String) Establece un nuevo delimitador de token.
n = sc.nextInt();
El método nextLine() extrae del buffer de entrada todos los caracteres hasta llegar a
un intro y elimina el intro del buffer.
En este caso asigna una cadena vacía a la variable nombre y limpia el intro. Esto
provoca que el programa no funcione correctamente, ya que no se detiene para que
se introduzca el nombre.
Solución:
sc.nextLine();
import java.util.Scanner;
public class JavaApplication335 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String nombre;
double radio;
int n;
System.out.print("Introduzca el radio de la circunferencia: ");
radio = sc.nextDouble();
System.out.println("Longitud de la circunferencia: " + 2*Math.PI*radio);
System.out.print("Introduzca un número entero: ");
n = sc.nextInt();
System.out.println("El cuadrado es: " + Math.pow(n,2));
System.out.print("Introduzca su nombre: ");
nombre = sc.nextLine(); //leemos el String después del double
System.out.println("Hola " + nombre + "!!!");
}
}
Si lo ejecutamos obtendremos:
Introduzca el radio de la circunferencia: 34
Longitud de la circunferencia: 213.62830044410595
Introduzca un número entero: 3
El cuadrado es: 9.0
Introduzca su nombre: Hola !!!
import java.util.Scanner;
public class JavaApplication335 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String nombre;
double radio;
int n;
System.out.print("Introduzca el radio de la circunferencia: ");
radio = sc.nextDouble();
System.out.println("Longitud de la circunferencia: " + 2*Math.PI*radio);
System.out.print("Introduzca un número entero: ");
n = sc.nextInt();
System.out.println("El cuadrado es: " + Math.pow(n,2));
sc.nextLine();
System.out.print("Introduzca su nombre: ");
nombre = sc.nextLine();
System.out.println("Hola " + nombre + "!!!");
}
}
OPERADOR DESCRIPCIÓN
+ Suma
– Resta
* Multiplicación
/ División
Programación en Java/Operadores
relacionales
< Programación en Java
Ir a la navegaciónIr a la búsqueda
Revisando algunas definiciones matemáticas, nos enteramos que los números conforman
un conjunto ordenado. Cada uno tiene una posición relativa. Sabemos que el 2 "es menor
que" el 4 y que el 6 "es más grande que" el 1. Al comparar dos números, realizamos una
función de relación.
En java disponemos de los operadores relacionales para verificar si se cumple una
relación. Por ejemplo el operador de equivalencia ( == ) nos devuelve un valor de
verdadero si los operandos son iguales. Estas operaciones comparan dos valores
numéricos y devuelven un valor booleano.
Operadores relacionales
== A == B verdadero si A es igual a B
!= A != B verdadero si A es distinto de B
No nos olvidemos de los char, que también participan. Podemos comparar caracteres,
pues internamente están almacenados como números.
char a = 'A';
char b = 'B';
boolean x = a > b;
Entre los booleanos solo se permiten los operadores de equivalencia, es igual (==) o es
distinto (!= )
boolean x = true;
boolean y = x == x;
boolean z = x != y;
Operadores de Relación.
Operador. Uso.
!= Distinto que…
Operador. Uso.
Operador OR. Para que la cóndición resultante final sea true, tan s
||
con que una fuese cierta.
int a= 3, b= 2;
if (a > b && a < 3)
{ // Si «a» es mayor que «b» y menor de «3» ejecuta la siguiente
sentencia.
System.out.
println (« La condición es
true.«);
// sentencia que NO se ejecutaría ya que si bien es cierto que «a» es mayor
que «b», no es menor de «3».
} else {
// Si no se cumple la condicion, ejecuta la siguiente sentencia.
System.
out.println («
La condición es false. «);
// sentencia que SI se ejecutaría.
}
Declaramos e inicializamos dos variables enteras y utilizamos el operador ||
(OR).
int a= 10, b= 12;
if (a > b || b >= 12) { // Si «a» es mayor que «b» ó «b» es mayor o igual a
«12» ejecuta la siguiente sentencia.
System.out.println (« La condición es true. «); // sentencia que SI
se ejecutaría aunque «a» no es mayor que «b», ya que «b» es igual a «12».
} else { // Si no se cumple la condicion, ejecuta la siguiente sentencia.
System.out.println (« La condición es false. «); // sentencia que
NO se ejecutaría.
}
Utilizamos el operador ! (NOT) sobre el ejemplo anterior.
int a= 10, b= 12;
if ( !(a > b || b >= 12) ) { // La condición resultaba antes como true tras
aplicar el operador ! (NOT)resultará false.
System.out.println (« La condición es true. «); // sentencia que NO
se ejecutaría.
} else { // Si no se cumple la condicion, ejecuta la siguiente sentencia.
System.out.println (« La condición es false. «); // sentencia que SI
se ejecutaría.
}
Si os fijais hemos tenido que añadir un paréntesis más, ya que no podemos
utilizar el que aporta la instrucción if.
Como norma general, cuando tengamos dudas en el orden de ejecución al
utilizar varios operadores, es decir, que no sepamos que operación se
ejecutará antes, es conveniente utilizar los paréntesis, de esta forma
estableceremos el orden de preferencia en la ejecución de una condición
determinada. Por ejemplo la condición siguiente:
Java provee distintas clases para el trabajo con cadenas de texto. La más básica, la clase String. Sin embargo
existen otras clases como StringBuffer y StringBuilder que resultan de interés porque facilitan cierto tipo de
trabajos y aportan mayor eficiencia en determinados contextos. Vamos a estudiarlas.
CLASE STRINGBUILDER
La clase StringBuilder es similar a la clase String en el sentido de que sirve para almacenar cadenas de
caracteres. No obstante, presenta algunas diferencias relevantes. Señalaremos como características de
StringBuilder a tener en cuenta:
- Su tamaño y contenido pueden modificarse. Los objetos de éste tipo son mutables. Esto es una
diferencia con los String.
- Debe crearse con alguno de sus costructores asociados. No se permite instanciar directamente a una
cadena como sí permiten los String.
- Un StringBuilder está indexado. Cada uno de sus caracteres tiene un índice: 0 para el primero,1 para el
segundo, etc.
- Los métodos de StringBuilder no están sincronizados. Esto implica que es más eficiente que StringBuffer
siempre que no se requiera trabajar con múltiples hilos (threads), que es lo más habitual.
Construye un StringBuilder
StringBuilder s = new
StringBuilder() vacío y con una capacidad por
StringBuilder();
defecto de 16 carácteres.
Se le pasa la capacidad
StringBuilder(int StringBuilder s = new
(número de caracteres) como
capacidad) StringBuilder(55);
argumento.
Construye un StringBuilder en
StringBuilder(String StringBuilder s = new
base al String que se le pasa
str) StringBuilder("hola");
como argumento.
Los métodos principales de StringBuilder se resumen en la siguiente tabla:
insert(int
Añade la cadena del segundo argumento a
StringBuilder indiceIni,String
partir de la posición indicada en el primero
cadena)
El método append será probablemente el más utilizado cuando trabajemos con esta clase.
CLASE STRINGBUFFER
La clase StringBuffer es similar a la clase StringBuilder, siendo la principal diferencia que sus métodos están
sincronizados, lo cual permite trabajar con múltiples hilos de ejecución (threads).
Los constructores y métodos de StringBuffer son los mismos que los de StringBuilder.
- StringBuffer y StringBuilder son mutables, mientras que String es inmutable. Cada vez que modificamos
un String se crea un objeto nuevo. Esto no ocurre con StringBuffer y StringBuilder.
- Los objetos String se almacenan en el Constant String Pool que es un repositorio o almacén de cadenas,
de valores de Strings. Esto se hace con el fin de que si creamos otro String, con el mismo valor, no se cree
un nuevo objeto sino que se use el mismo y se asigne una referencia al objeto ya creado. Los objetos
StringBuffer y StringBuilder se almacenan en el heap que es otro espacio de memoria usado en tiempo de
ejecución para almacenar las instancias de clases, objetos y arrays. Realmente no nos interesa entrar a nivel
de detalle en estas diferencias: simplemente, recordar que los objetos String tienen diferente
tratamiento que los StringBuffer y StringBuilder.
¿Cómo decidir qué clase usar? Normalmente usaremos la clase String. No obstante, en algunos casos puede
ser de interés usar StringBuffer o StringBuilder. A continuación damos algunas indicaciones útiles para elegir:
- Si el valor del objeto no va a cambiar o va a cambiar poco, entonces es mejor usar String, la clase más
convencional para el trabajo con cadenas.
- Si el valor del objeto puede cambiar gran número de veces y puede ser modificado por más de un hilo
(thread) la mejor opción es StringBuffer porque es thread safe (sincronizado). Esto asegura que un hilo no
puede modificar el StringBuffer que está siendo utilizado por otro hilo.
- Si el valor del objeto puede cambiar gran número de veces y solo será modificado por un mismo hilo o
thread (lo más habitual), entonces usamos StringBuilder, ya que al no ser sincronizado es más rápido y tiene
mejor rendimiento. El propio api de Java recomienda usar StringBuilder con preferencia sobre
StringBuffer, excepto si la situación requiere sincronización. En esencia la multitarea (trabajar con varios
thread) nos permite ejecutar varios procesos a la vez “en paralelo”. Es decir, de forma concurrente y por
tanto eso nos permite hacer programas que se ejecuten en menor tiempo y sean más eficientes. Esto ya lo
veremos con más detalle más adelante.
Vamos a ver un ejemplo en el que mediremos el rendimiento de StringBuilder y StringBuffer Para ello vamos
a concatener un millón de String ("Elefante") a un StringBuilder y a un StringBuffer, y compararemos los
tiempos. El código que ejecutaremos será el siguiente:
Los resultados que obtendremos pueden ser variables. ¿Por qué? Porque el tiempo de ejecución depende
de muchos factores, por ejemplo del computador que utilicemos, estado del procesador en el momento de
la ejecución, etc. En general el resultado será que StringBuilder es más rápido para ejecutar esta tarea. Por
ejemplo podemos obtener
No obstante, podrías encontrarte con que en algunas ejecuciones el tiempo que te marca StringBuffer sea
menor debido a lo que hemos indicado anteriormente: el tiempo de ejecución depende de muchos factores.
No obstante, lo importante es quedarnos con la idea de que a no ser que sea realmente necesario, será
preferible usar StringBuilder antes que String Buffer.
La misma prueba con el operador de suma consumiría una gran cantidad de tiempo, ya que la creación
constante de nuevos objetos hace que la JVM tenga que empezar a limpiar continuamente el Heap. A modo
de referencia, concatener tan sólo 100.000 String con el operador de suma se puede demorar por ejemplo
100000 milisegundos frente a por ejemplo 90 milisegundos con StringBuilder, por lo que su rendimiento no
tiene comparación para este tipo de procesos.
CONCLUSIONES
Para los usos más habituales usaremos String, la clase convencional prevista por Java para trabajar con
cadenas. En situaciones especiales en que se requiera realizar muchas modificaciones de un String (por
ejemplo ir concatenándole sucesivos fragmentos) la opción recomendada es usar StringBuilder.
Recurriremos a StringBuffer sólo cuando trabajemos en entorno multihilos.
Cabe preguntarse. ¿Por qué existen distintas clases para realizar tareas tan parecidas? ¿No sería preferible
tener una sola clase y de alguna manera especificar cómo queremos que trabaje? La respuesta es que
quizás. Los motivos por los que existen varias clases son:
- Motivos históricos. Han ido apareciendo nuevas clases a medida que Java evolucionaba.
- Motivos de diseño del lenguaje y compilador Java. Los creadores de Java diseñan el lenguaje de la forma
que les parece más adecuada. Casi siempre aciertan (y a veces se equivocan).
EJERCICIO
c) Partiendo de la cadena anterior y usando los métodos de StringBuilder modificar la cadena para que
pase a ser "Hay Caracolas" y mostrarla por consola.
d) Partiendo de la cadena anterior y usando los métodos de StringBuilder modificar la cadena para que
pase a ser "Hay 5000 Caracolas" y mostrarla por consola. El número entero 5000 debe estar almacenado
en un int inicialmente.
e) Partiendo de la cadena anterior y usando los métodos de StringBuilder modificar la cadena para que
pase a ser "Hay 5000 Caracolas en el mar" y mostrarla por consola.
f) Almacenar en un String los últimos 4 carácteres del StringBuilder resultante y mostrar ese String por
consola.
Ejemplo de ejecución:
class GFG {
{
StringBuffer s = new StringBuffer("GeeksforGeeks");
int p = s.length();
int q = s.capacity();
Output:
class GFG {
s.append("Geeks");
s.append(1);
Output:
GeeksforGeeks
GeeksforGeeks1
insert( ): It is used to insert text at the specified index position. These are a few
of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
Here, index specifies the index at which point the string will be inserted
into the invoking StringBuffer object.
Code Example:
filter_none
edit
play_arrow
brightness_4
import java.io.*;
class GFG {
s.insert(5, "for");
s.insert(0, 5);
s.insert(3, true);
s.insert(5, 41.35d);
s.insert(8, 41.35f);
s.insert(2, geeks_arr);
Output:
GeeksforGeeks
5GeeksforGeeks
5GetrueeksforGeeks
5Getr41.35ueeksforGeeks
5Getr41.41.3535ueeksforGeeks
5Gpawanetr41.41.3535ueeksforGeeks
reverse( ): It can reverse the characters within a StringBuffer object
using reverse( ).This method returns the reversed object on which it was called.
Code Example:
filter_none
edit
play_arrow
brightness_4
import java.io.*;
class GFG {
s.reverse();
Output:
skeeGskeeG
delete( ) and deleteCharAt( ): It can delete characters within a StringBuffer by
using the methods delete( ) and deleteCharAt( ).The delete( ) method deletes a
sequence of characters from the invoking object. Here, start Index specifies the
index of the first character to remove, and end Index specifies an index one past
the last character to remove. Thus, the substring deleted runs from start Index to
endIndex–1. The resulting StringBuffer object is returned. The deleteCharAt(
) method deletes the character at the index specified by loc. It returns the
resulting StringBuffer object.These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
Code Example:
filter_none
edit
play_arrow
brightness_4
import java.io.*;
class GFG {
s.delete(0, 5);
s.deleteCharAt(7);
Output:
forGeeks
forGeek
replace( ): It can replace one set of characters with another set inside a
StringBuffer object by calling replace( ). The substring being replaced is specified
by the indexes start Index and endIndex. Thus, the substring at start
Index through endIndex–1 is replaced. The replacement string is passed in
str.The resulting StringBuffer object is returned.Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
Code Example:
filter_none
edit
play_arrow
brightness_4
import java.io.*;
class GFG {
Output:
GeeksareGeeks
ensureCapacity( ): It is used to increase the capacity of a StringBuffer object.
The new capacity will be set to either the value we specify or twice the current
capacity plus two (i.e. capacity+2), whichever is larger. Here, capacity specifies
the size of the buffer.
void ensureCapacity(int capacity)
Besides that all the methods that are used in String class can also be
used.
StringBuffer appendCodePoint(int codePoint): This method appends the
string representation of the codePoint argument to this sequence.
Syntax:
public StringBuffer appendCodePoint(int codePoint)
char charAt(int index): This method returns the char value in this sequence at
the specified index.
Syntax:
public char charAt(int index)
IntStream chars(): This method returns a stream of int zero-extending the char
values from this sequence.
Syntax:
public IntStream chars()
int codePointAt(int index): This method returns the character (Unicode code
point) at the specified index.
Syntax:
public int codePointAt(int index)
int codePointBefore(int index): This method returns the character (Unicode
code point) before the specified index.
Syntax:
public int codePointBefore(int index)
int codePointCount(int beginIndex, int endIndex): This method returns the
number of Unicode code points in the specified text range of this sequence.
Syntax:
public int codePointCount(int beginIndex,
int endIndex)
IntStream codePoints(): This method returns a stream of code point values from
this sequence.
Syntax:
public IntStream codePoints()
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): In this
method, the characters are copied from this sequence into the destination
character array dst.
Syntax:
public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
int indexOf(String str): This method returns the index within this string of the first
occurrence of the specified substring.
Syntax:
public int indexOf(String str)
Recommended Posts:
StringBuffer insert() in Java
A Java Random and StringBuffer Puzzle
StringBuffer subSequence() in Java with Examples
String vs StringBuilder vs StringBuffer in Java
StringBuffer setLength() in Java with Examples
StringBuffer trimToSize() method in Java with Examples
StringBuffer deleteCharAt() Method in Java with Examples
StringBuffer codePointCount() method in Java with Examples
StringBuffer codePointBefore() method in Java with Examples
StringBuffer append() Method in Java with Examples
StringBuffer delete() Method in Java with Examples
StringBuffer reverse() Method in Java with Examples
StringBuffer appendCodePoint() Method in Java with Examples
StringBuffer setCharAt() method in Java with Examples
StringBuffer getChars() method in Java with Examples
Class BufferedReader
java.lang.Object
java.io.Reader
java.io.BufferedReader
Reads text from a character-input stream, buffering characters so as to provide for the efficient
reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for
most purposes.
In general, each read request made of a Reader causes a corresponding read request to be made
of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader
around any Reader whose read() operations may be costly, such as FileReaders and
InputStreamReaders. For example,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine()
could cause bytes to be read from the file, converted into characters, and then returned, which can
be very inefficient.
Programs that use DataInputStreams for textual input can be localized by replacing each
DataInputStream with an appropriate BufferedReader.
Since:
JDK1.1
See Also:
FileReader, InputStreamReader, Files.newBufferedReader(java.n
io.file.Path, java.nio.charset.Charset)
Field Summary
lock
Constructor Summary
Constructors
BufferedReader(Reader in)
Creates a buffering character-input stream that uses a default-sized input buffer.
Method Summary
Methods
void close()
Closes the stream and releases any system resources
boolean markSupported()
Tells whether this stream supports the mark() opera
int read()
Reads a single character.
int read(char[] cbuf, int off,
Reads characters into a portion of an array.
String readLine()
Reads a line of text.
boolean ready()
Tells whether this stream is ready to be read.
void reset()
Resets the stream to the most recent mark.
long skip(long n)
Skips characters.
read, read
Methods inherited from class java.lang.Object
Constructor Detail
BufferedReader
public BufferedReader(Reader in,
int sz)
Creates a buffering character-input stream that uses an input buffer of the specified size.
Parameters:
in - A Reader
sz - Input-buffer size
Throws:
IllegalArgumentException - If sz is <= 0
BufferedReader
public BufferedReader(Reader in)
Creates a buffering character-input stream that uses a default-sized input buffer.
Parameters:
in - A Reader
Method Detail
read
public int read()
throws IOException
Overrides:
Returns:
The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of
the stream has been reached
Throws:
read
public int read(char[] cbuf,
int off,
int len)
throws IOException
This method implements the general contract of the corresponding read method of
the Reader class. As an additional convenience, it attempts to read as many characters as possible by
repeatedly invoking the read method of the underlying stream. This iterated readcontinues until one of
the following conditions becomes true:
If the first read on the underlying stream returns -1 to indicate end-of-file then this method returns -1.
Otherwise this method returns the number of characters actually read.
Subclasses of this class are encouraged, but not required, to attempt to read as many characters as
possible in the same fashion.
Ordinarily this method takes characters from this stream's character buffer, filling it from the underlying
stream as necessary. If, however, the buffer is empty, the mark is not valid, and the requested length is at
least as large as the buffer, then this method will read characters directly from the underlying stream into
the given array. Thus redundant BufferedReaders will not copy data unnecessarily.
Specified by:
Parameters:
Returns:
The number of characters read, or -1 if the end of the stream has been reached
Throws:
readLine
public String readLine()
throws IOException
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return
('\r'), or a carriage return followed immediately by a linefeed.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if
the end of the stream has been reached
Throws:
See Also:
Files.readAllLines(java.nio.file.Path,
java.nio.charset.Charset)
skip
public long skip(long n)
throws IOException
Skips characters.
Overrides:
Parameters:
n - The number of characters to skip
Returns:
Throws:
IllegalArgumentException - If n is negative.
IOException - If an I/O error occurs
ready
public boolean ready()
throws IOException
Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not
empty, or if the underlying character stream is ready.
Overrides:
Returns:
True if the next read() is guaranteed not to block for input, false otherwise. Note that returning
false does not guarantee that the next read will block.
Throws:
markSupported
public boolean markSupported()
Tells whether this stream supports the mark() operation, which it does.
Overrides:
Returns:
mark
public void mark(int readAheadLimit)
throws IOException
Marks the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream
to this point.
Overrides:
readAheadLimit - Limit on the number of characters that may be read while still preserving
the mark. An attempt to reset the stream after reading characters up to this limit or beyond may
fail. A limit value larger than the size of the input buffer will cause a new buffer to be allocated
whose size is no smaller than limit. Therefore large values should be used with care.
Throws:
reset
public void reset()
throws IOException
Overrides:
Throws:
IOException - If the stream has never been marked, or if the mark has been invalidated
close
public void close()
throws IOException
Closes the stream and releases any system resources associated with it. Once the stream has been
closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a
previously closed stream has no effect.
Specified by:
Specified by:
Specified by:
Throws: