Java >> Programma Java >  >> Tag >> java.io

Classe Java.io.Reader in Java

È una classe astratta per leggere i flussi di caratteri. Gli unici metodi che una sottoclasse deve implementare sono read(char[], int, int) e close(). La maggior parte delle sottoclassi, tuttavia, sovrascriverà alcuni dei metodi qui definiti per fornire maggiore efficienza, funzionalità aggiuntive o entrambi.
Costruttori:

  • Lettore protetto() : Crea un nuovo lettore del flusso di caratteri le cui sezioni critiche si sincronizzeranno sul lettore stesso.
  • Lettore protetto (Blocco oggetto) : Crea un nuovo lettore di flussi di caratteri le cui sezioni critiche verranno sincronizzate sull'oggetto specificato.

Metodi:

  • abstract void close() : Chiude il flusso e rilascia tutte le risorse di sistema ad esso associate. Una volta che lo stream è stato chiuso, ulteriori invocazioni read(), ready(), mark(), reset() o skip() genereranno una IOException. La chiusura di uno stream precedentemente chiuso non ha effetto.
    Syntax :public abstract void close()
                        throws IOException
    Throws:
    IOException 
  • segno di vuoto(int readAheadLimit) : Contrassegna la posizione attuale nel flusso. Le chiamate successive a reset() tenteranno di riposizionare il flusso fino a questo punto. Non tutti i flussi di input di caratteri supportano l'operazione mark().
    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. After reading this many characters, 
    attempting to reset the stream may fail.
    Throws:
    IOException 
  • boolean markSupported() : Indica se questo flusso supporta l'operazione mark(). L'implementazione predefinita restituisce sempre false. Le sottoclassi dovrebbero sovrascrivere questo metodo.
    Syntax :public boolean markSupported()
    Returns:
    true if and only if this stream supports the mark operation.
  • int read() : Legge un singolo carattere. Questo metodo si bloccherà fino a quando non sarà disponibile un carattere, si verificherà un errore di I/O o verrà raggiunta la fine del flusso.
    Le sottoclassi che intendono supportare un input efficiente a carattere singolo dovrebbero ignorare questo metodo.

    Syntax :public int read()
             throws IOException
    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:
    IOException 
  • int read(char[] cbuf) : Legge i caratteri in un array. Questo metodo si bloccherà finché non sarà disponibile un input, si verifica un errore di I/O o viene raggiunta la fine del flusso.
    Syntax :public int read(char[] cbuf)
             throws IOException
    Parameters:
    cbuf - Destination buffer
    Returns:
    The number of characters read, or -1 if the end of the stream has been reached
    Throws:
    IOException 
  • abstract int read(char[] cbuf, int off, int len) : Legge i caratteri in una parte di una matrice. Questo metodo si bloccherà finché non sarà disponibile un input, si verifica un errore di I/O o viene raggiunta la fine del flusso.
    Syntax :public abstract int read(char[] cbuf,
           int off,
           int len)
                      throws IOException
    Parameters:
    cbuf - Destination buffer
    off - Offset at which to start storing 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 
  • int read(destinazione CharBuffer) : Tenta di leggere i caratteri nel buffer di caratteri specificato. Il buffer viene utilizzato come repository di caratteri così come sono:le uniche modifiche apportate sono i risultati di un'operazione di immissione. Non viene eseguito alcun capovolgimento o riavvolgimento del buffer.
    Syntax :public int read(CharBuffer target)
             throws IOException
    Parameters:
    target - the buffer to read characters into
    Returns:
    The number of characters added to the buffer, 
    or -1 if this source of characters is at its end
    Throws:
    IOException 
    NullPointerException
    ReadOnlyBufferException
  • booleano pronto() : Indica se questo stream è pronto per essere letto.
    Syntax :public boolean ready()
                  throws IOException
    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:
    IOException 
  • ripristino nullo() : Reimposta il flusso. Se il flusso è stato contrassegnato, provare a riposizionarlo in corrispondenza del contrassegno. Se il flusso non è stato contrassegnato, prova a reimpostarlo in un modo appropriato per il flusso particolare, ad esempio riposizionandolo al punto iniziale. Non tutti i flussi di input di caratteri supportano l'operazione reset() e alcuni supportano reset() senza supportare mark().
    Syntax :public void reset()
               throws IOException
    Throws:
    IOException
  • salto lungo(n lungo) : Salta i caratteri. Questo metodo si bloccherà finché alcuni caratteri non saranno disponibili, si verifica un errore di I/O o viene raggiunta la fine del flusso.
    Syntax :public long skip(long n)
              throws IOException
    Parameters:
    n - The number of characters to skip
    Returns:
    The number of characters actually skipped
    Throws:
    IllegalArgumentException - If n is negative.
    IOException




//Java program demonstrating Reader methods import java.io.*; import java.nio.CharBuffer; import java.util.Arrays; class ReaderDemo {      public static void main(String[] args) throws IOException      {          Reader r = new FileReader( "file.txt" );          PrintStream out = System.out;          char c[] = new char [ 10 ];          CharBuffer cf = CharBuffer.wrap(c);            //illustrating markSupported()          if (r.markSupported()) {              //illustrating mark()              r.mark( 100 );              out.println( "mark method is supported" );          }          //skipping 5 characters          r.skip( 5 );            //checking whether this stream is ready to be read.          if (r.ready())           {              //illustrating read(char[] cbuf,int off,int len)              r.read(c, 0 , 10 );              out.println(Arrays.toString(c));                //illustrating read(CharBuffer target )              r.read(cf);              out.println(Arrays.toString(cf.array()));                            //illustrating read()              out.println(( char )r.read());          }          //closing the stream          r.close();      } }

 

 

Risultato :

[f, g, h, i, g, k, l, m, n, o]
[p, q, r, s, t, u, v, w, x, y]
z

Questo articolo è fornito da Nishant Sharma . Se ti piace GeeksforGeeks e vorresti contribuire, puoi anche scrivere un articolo utilizzando contribuire.geeksforgeeks.org o inviare il tuo articolo per posta a [email protected]. Guarda il tuo articolo che appare nella pagina principale di GeeksforGeeks e aiuta altri Geeks.

Scrivi commenti se trovi qualcosa di errato o se desideri condividere maggiori informazioni sull'argomento discusso sopra.


Etichetta Java