logo

Classe Java StreamTokenizer - Set 1

A Giava il StreamTokenizer la classe è presente in pacchetto java.io . Viene utilizzato per analizzare un flusso di input suddividendolo in piccoli blocchi noti come gettoni questi token facilitano l'elaborazione. Un token può essere una parola, un numero o qualsiasi simbolo specifico. Stream Tokenizer è in grado di riconoscere numeri, stringhe tra virgolette e vari stili di commento.

Caratteristiche della classe StreamTokenizer:

Le caratteristiche principali della classe StreamTokenizer sono elencate di seguito:



  • Suddivide i flussi di input in token come simboli, parole e numeri.
  • Supporta il monitoraggio dei numeri di riga.
  • Può trattare i caratteri di fine riga come token.
  • Può anche convertire automaticamente i token di parole in lettere minuscole.

Dichiarazione della classe StreamTokenizer

La dichiarazione della classe StreamTokenizer è:

la classe pubblica StreamTokenizer estende l'oggetto implementa Serializable

Nota: Estende Object e implementa Serializable.

Costruttori della classe StreamTokenizer

Questa classe è composta da due costruttori con l'aiuto dei quali possiamo creare oggetti di questa classe in diversi modi. Di seguito sono riportati i costruttori disponibili in questa classe:

1. StreamTokenizer (InputStream è): Questo costruttore è deprecato . È un modo più vecchio per creare un tokenizzatore direttamente da un flusso di byte.

Sintassi:

StreamTokenizer(InputStream è)

Nota: Questo non è raccomandato perché funziona su byte e non su caratteri.

2. StreamTokenizer(Lettore r): Questo è il modo migliore per creare un tokenizzatore: utilizza un flusso di caratteri che gestisce correttamente il testo.

Sintassi:

StreamTokenizer(Lettore r)

Esempio:

Java
// Demonstrating the working  // of StreamTokenizer(Reader r)  import java.io.*; public class Geeks {    public static void main(String[] args) throws IOException {    Reader r = new StringReader('Hello 123');  StreamTokenizer t = new StreamTokenizer(r);     int token;  while ((token = t.nextToken()) != StreamTokenizer.TT_EOF) {  if (token == StreamTokenizer.TT_WORD) {  System.out.println('Word: ' + t.sval);  } else if (token == StreamTokenizer.TT_NUMBER) {  System.out.println('Number: ' + t.nval);  }  }  } } 

Produzione
Word: Hello Number: 123.0 


stringa su int in Java

Metodi Java StreamTokenizer

La tabella seguente mostra i metodi di questa classe.

MetodoDescrizione
commentoChar()Specifica che il carattere ch inizia un commento a riga singola. Tutti i caratteri dal carattere di commento alla fine della riga vengono ignorati.
linea()Restituisce il numero di riga corrente del flusso di input.
aString()Restituisce una rappresentazione di stringa del token del flusso corrente e il numero di riga in cui si trova.

eolIsSignificant(flag booleano)

Determina se i caratteri di fine riga vengono trattati come token significativi. Se i veri caratteri di fine riga vengono restituiti come token.

ordinarioChar(int ch)Specifica che il carattere ch viene trattato come un carattere ordinario e non come un numero di parola o un carattere di commento.
token successivo()Analizza il token successivo dal flusso di input e ne restituisce il tipo.
lowerCaseMode()Determina se i token di parole vengono automaticamente convertiti in lettere minuscole.
ordinarioChar()Specifica che il carattere ch viene trattato come un carattere normale.
caratteriordinari()Specifica che tutti i caratteri nell'intervallo dal basso all'alto vengono trattati come caratteri normali.


Ora discuteremo di ciascun metodo uno per uno in dettaglio:


1. commentoCar(): Questo metodo viene utilizzato per specificare il carattere cap che inizia con un commento a riga singola e tutti i caratteri da questo carattere fino alla fine della riga non vengono riconosciuti da StreamTokenizer.

Sintassi:

public void commentChar(int ch)

  • Parametro: Questo metodo accetta un singolo valore intero cap dopodiché tutti i personaggi vengono ignorati
  • Tipo di reso: Questo metodo non restituisce nulla.

Esempio:

Java
// Demonstrating the working of commentChar() method import java.io.*; public class Geeks {  public static void main(String[] args) throws IOException {  FileReader reader = new FileReader('ABC.txt');  BufferedReader bufferread = new BufferedReader(reader);  StreamTokenizer token = new StreamTokenizer(bufferread);  // Use of commentChar() method  token.commentChar('a');   int t;  while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) {  switch (t) {  case StreamTokenizer.TT_NUMBER:  System.out.println('Number : ' + token.nval);  break;  case StreamTokenizer.TT_WORD:  System.out.println('Word : ' + token.sval);  break;  }  }  } } 

Produzione:

Word : Programmers  
Number : 1.0
Number : 2.0
Number : 3.0
Word : Geeks
Word : Hello
Word : a
Word : Program
Word : is
Word : explained
Word : here
Word : my
Word : friends.

Nota: Questo programma non verrà eseguito correttamente perché il file "ABC.txt" non esiste. Se vogliamo testare il codice sul sistema dobbiamo semplicemente creare il nome del file ABC.txt.

Crea un file ABC.txt con il seguente contenuto elencato di seguito:

Programmatori 1 2 3 Geeks Ciao a Il programma è spiegato qui amici miei.


2. riga(): Questo metodo restituisce il numero di riga corrente elaborato da StreamTokenizer. Questo metodo è molto utile quando vogliamo verificare come funziona l'elaborazione, eseguire il debug del programma e possiamo anche tenere traccia dei numeri di riga durante il momento della tokenizzazione.

Sintassi:

public int lino()

  • Parametro: Questo metodo non accetta alcun parametro.
  • Tipo di reso: Questo metodo restituisce un valore int corrispondente al numero di riga del flusso di input corrente.

Esempio:

Java
// Demonstrating the use of lineno() method import java.io.*; public class Geeks {  public static void main(String[] args) throws InterruptedException   FileNotFoundException IOException  {  FileReader reader = new FileReader('ABC.txt');  BufferedReader bufferread = new BufferedReader(reader);  StreamTokenizer token = new StreamTokenizer(bufferread);    token.eolIsSignificant(true);  // Use of lineno() method   // to get current line no.  System.out.println('Line Number:' + token.lineno());  token.commentChar('a');  int t;  while ((t = token.nextToken()) != StreamTokenizer.TT_EOF)  {  switch (t)  {  case StreamTokenizer.TT_EOL:  System.out.println('');  System.out.println('Line No. : ' + token.lineno());  break;  case StreamTokenizer.TT_NUMBER:  System.out.println('Number : ' + token.nval);  break;  case StreamTokenizer.TT_WORD:  System.out.println('Word : ' + token.sval);  break;  }  }  } } 

Produzione:

Line Number:1  
Word : Progr

Line No. : 2
Number : 1.0

Line No. : 3
Number : 2.0

Line No. : 4
Number : 3.0

Line No. : 5
Word : Geeks

Line No. : 6
Word : Hello

Line No. : 7
Word : This
Word : is


Jasmine Davis da bambina

3. toString(): Questo metodo restituisce una stringa che rappresenta il token del flusso corrente con il valore del token e il numero di riga attualmente utilizzato.

Sintassi:

Stringa pubblica toString()

  • Parametro: Questo metodo non accetta alcun parametro.
  • Tipo di reso: Questo metodo restituisce un valore stringa che rappresenta il token del flusso corrente con il numero di riga.

Esempio:

Java
// Demonstrating the use of toString() method import java.io.*; public class Geeks {  public static void main(String[] args) throws IOException {  FileReader reader = new FileReader('ABC.txt');  BufferedReader bufferread = new BufferedReader(reader);  StreamTokenizer token = new StreamTokenizer(bufferread);  int t;  while ((t = token.nextToken()) != StreamTokenizer.TT_EOF) {  switch (t) {  case StreamTokenizer.TT_NUMBER:  System.out.println('Number : ' + token.nval);  break;  case StreamTokenizer.TT_WORD:  System.out.println('Word : ' + token.toString());   break;  }  }  } } 

Produzione:

Word : Token[Programmers] line 1  
Number : 1.0
Number : 2.0
Number : 3.0
Word : Token[Geeks] line 5
Word : Token[Hello] line 6
Word : Token[a] line 7
Word : Token[Program] line 7
Word : Token[is] line 7
Word : Token[explained] line 7
Word : Token[here] line 7
Word : Token[my] line 7
Word : Token[friends.] line 7


4. eolIsSignificant(): Questo metodo non restituisce nulla ma viene utilizzato per verificare se il carattere EOL (End of Line) deve essere tokenizzato. Se il flag è vero, ogni carattere di fine riga viene trattato come un token e gli viene assegnato il tipo di token TT_EOL, il carattere eol viene ignorato e trattato come uno spazio bianco.

Sintassi:

public void eolIsSignificant(flag booleano)

  • Parametro: Questo metodo accetta un valore booleano bandiera se è vero, il carattere di fine riga viene trattato come un token o ignorato come uno spazio bianco.
  • Tipo di reso: Questo metodo non restituisce nulla.

Esempio:

Java
// Demonstrating the use of eolIsSignificant() method import java.io.*; public class Geeks {  public static void main(String[] args) throws InterruptedException  FileNotFoundException IOException  {  FileReader reader = new FileReader('ABC.txt');  BufferedReader bufferread = new BufferedReader(reader);  StreamTokenizer token = new StreamTokenizer(bufferread);  boolean arg = true;  // Use of eolIsSignificant() method  token.eolIsSignificant(arg);  // Here the 'arg' is set true so EOL is treated as a token  int t;  while ((t = token.nextToken()) != StreamTokenizer.TT_EOF)  {  switch (t)  {  case StreamTokenizer.TT_EOL:  System.out.println('End of Line encountered.');  break;  case StreamTokenizer.TT_NUMBER:  System.out.println('Number : ' + token.nval);  break;  case StreamTokenizer.TT_WORD:  System.out.println('Word : ' + token.sval);  break;  }  }  } } 

Produzione:

Number : 1.0  
End of Line encountered.
Word : Geeks
End of Line encountered.
Number : 2.0
End of Line encountered.
Word : For
End of Line encountered.
Number : 3.0
End of Line encountered.
Word : Geeks

Nota: Questo programma non verrà eseguito correttamente perché il file "ABC.txt" non esiste. Se vogliamo testare il codice sul sistema dobbiamo semplicemente creare il nome del file ABC.txt.

Crea un file ABC.txxt con il seguente contenuto elencato di seguito:

1 Geek 2 Per 3 Geek


5. nextToken(): Questo metodo legge il token successivo dal flusso di input e restituisce il tipo. Il tipo del token è memorizzato nel file ttype campo. Restituisce il tipo come valore intero che può essere TT_WORD TT_NUMBER e TT_EOL e così via.

Sintassi:

public int nextToken()

connessione java mysql
  • Parametro: Questo metodo non accetta alcun parametro.
  • Tipo di reso: Questo metodo restituisce il file int valore del tipo di token.

Esempio:

Java
// Demonstrating the use of nextToken() method import java.io.*; public class Geeks {  public static void main(String[] args) throws InterruptedException  FileNotFoundException IOException  {  FileReader reader = new FileReader('ABC.txt');  BufferedReader bufferread = new BufferedReader(reader);  StreamTokenizer token = new StreamTokenizer(bufferread);  // Use of nextToken() method to parse Next Token from the Input Stream  int t = token.nextToken();  while ((t = token.nextToken()) != StreamTokenizer.TT_EOF)  {  switch (t)  {  case StreamTokenizer.TT_NUMBER:  System.out.println('Number : ' + token.nval);  break;  case StreamTokenizer.TT_WORD:  System.out.println('Word : ' + token.sval);  break;  }  }  } } 

Produzione:

Word : This  
Word : program
Word : tells
Number : 2.0
Word : about
Word : use
Word : of
Number : 3.0
Word : next
Word : token
Word : method

Nota: Questo programma non verrà eseguito correttamente perché il file "ABC.txt" non esiste. Se vogliamo testare il codice sul sistema dobbiamo semplicemente creare il nome del file ABC.txt.

Crea un file ABC.txt con il seguente contenuto elencato di seguito:

1 Questo programma informa 2 sull'uso del 3 metodo successivo token()


6. lowerCaseMod(): Questo metodo accetta un valore booleano bandiera valore e controlla se il token deve essere convertito automaticamente in minuscolo. Se il flag è vero, tutte le parole del token vengono convertite in minuscolo o altrimenti i token vengono impostati così come sono e non vogliono convertirli.

Sintassi:

public void lowerCaseMode(flag booleano)

java math.random
  • Parametro: Ci vuole un valore booleano bandiera valore. Se è vero, tutti i token verranno convertiti in minuscolo e se falso, non verranno convertiti.
  • Tipo di reso: Questo metodo non restituisce nulla.

Esempio:

Java
// Demonstrating the use of lowerCaseMode() method import java.io.*; public class NewClass {  public static void main(String[] args) throws InterruptedException  FileNotFoundException IOException  {  FileReader reader = new FileReader('ABC.txt');  BufferedReader bufferread = new BufferedReader(reader);  StreamTokenizer token = new StreamTokenizer(bufferread);  // Use of lowerCaseMode() method to  //Here the we have set the Lower Case Mode ON    boolean arg = true;  token.lowerCaseMode(arg);  int t;  while ((t = token.nextToken()) != StreamTokenizer.TT_EOF)  {  switch (t)  {  case StreamTokenizer.TT_NUMBER:  System.out.println('Number : ' + token.nval);  break;  case StreamTokenizer.TT_WORD:  System.out.println('Word : ' + token.sval);  break;  }  }  } } 

Produzione:

Word : hello  
Word : geeks
Word : this
Word : is
Word : about
Word : lowercasemode

Nota: Questo programma non verrà eseguito correttamente perché il file "ABC.txt" non esiste. Se vogliamo testare il codice sul sistema dobbiamo semplicemente creare il nome del file ABC.txt.

Crea un file ABC.txt con il seguente contenuto elencato di seguito:

Ciao geek, si tratta di LowerCaseMode()


7. ordinarioChar(): Questo metodo accetta un valore int cap dovrebbe essere trattato come un personaggio. Utilizzando questo metodo possiamo trattare a carattere UN come carattere speciale come una parola numerica o uno spazio bianco.

Sintassi:

public void ordinarioChar(int ch)

  • Parametro: Questo metodo richiede un singolo int cap valore che verrà trattato come un carattere.
  • Tipo di reso: Questo metodo non restituisce nulla.

Esempio:

Java
// Demonstrating the use of ordinaryChar() method import java.io.*; public class Geeks {  public static void main(String[] args) throws InterruptedException  FileNotFoundException IOException  {  FileReader reader = new FileReader('ABC.txt');  BufferedReader bufferread = new BufferedReader(reader);  StreamTokenizer token = new StreamTokenizer(bufferread);  // Use of ordinaryChar() method   // Here we have taken 's' as an ordinary character  token.ordinaryChar('s');  int t;  while ((t = token.nextToken()) != StreamTokenizer.TT_EOF)  {  switch (t)  {  case StreamTokenizer.TT_NUMBER:  System.out.println('Number : ' + token.nval);  break;  case StreamTokenizer.TT_WORD:  System.out.println('Word : ' + token.sval);  break;  }  }  } } 

Produzione:

Word : Hello  
Word : Geek
Word : Thi
Word : I
Word : zz
Word : About
Word : ordinaryChar

Nota: Questo programma non verrà eseguito correttamente perché il file "ABC.txt" non esiste. Se vogliamo testare il codice sul sistema dobbiamo semplicemente creare il nome del file ABC.txt.

Crea un file ABC.txt con il seguente contenuto elencato di seguito:

Ciao geeks Thissss Issszz Informazioni su ordinarioChar() Questo metodo ha rimosso 's' dall'intero flusso


8. caratteriordinari(): Questo metodo specifica che tutti i caratteri nell'intervallo dal basso all'alto (incluso) verranno trattati come caratteri normali e dopo aver chiamato questo metodo i caratteri non verranno più trattati come caratteri speciali.

Sintassi:

public void ordinarioChars(int low int high)

  • Parametro: Questo metodo accetta due valori interi Basso E alto ( compreso) l'intervallo del carattere che viene convertito in un carattere speciale.
  • Tipo di reso: Questo metodo non restituisce nulla.

Esempio:

Java
// Demonstrating the use of ordinaryChars() method import java.io.*; public class Geeks {  public static void main(String[] args) throws InterruptedException  FileNotFoundException IOException  {  FileReader reader = new FileReader('ABC.txt');  BufferedReader bufferread = new BufferedReader(reader);  StreamTokenizer token = new StreamTokenizer(bufferread);  // Use of ordinaryChars() method   // Here we have taken low = 'a' and high = 'c'   token.ordinaryChars('a''c');  int t;  while ((t = token.nextToken()) != StreamTokenizer.TT_EOF)  {  switch (t)  {  case StreamTokenizer.TT_NUMBER:  System.out.println('Number : ' + token.nval);  break;  case StreamTokenizer.TT_WORD:  System.out.println('Word : ' + token.sval);  break;  }  }  } } 

Produzione:

Word : Hello  
Word : Geeks
Word : This
Word : is
Word : out
Word : ordin
Word : ryCh
Word : rs

Nota: Questo programma non verrà eseguito correttamente perché il file "ABC.txt" non esiste. Se vogliamo testare il codice sul sistema dobbiamo semplicemente creare il nome del file ABC.txt.

Crea un file ABC.txt con il seguente contenuto elencato di seguito:

Ciao Geeks, si tratta di ordinariChars()


Utilizzo di StreamTokenizer per tokenizzare un file di testo

La classe StreamTokenizer viene utilizzata anche per tokenizzare il file di testo e qui stiamo utilizzando i metodi della metodologia della classe Tokenizer.

Passaggio 1: Per prima cosa crea un file di testo con .TXT estensione nella stessa directory root. Qui lo abbiamo creato con il nome Geeks.txt .

File di testo' title=



Passaggio 2: Ora crea un file Java e scrivi il codice per tokenizzare i dati di testo presenti nel file di testo.

File Geeks.java:

java int in stringa
Java
// Java program to Tokenized the text  // file data using StreamTokenizer methods import java.io.*;  public class Geeks {   public static void main(String[] args) throws InterruptedException   FileNotFoundException IOException   {   FileReader reader = new FileReader('Geeks.txt');   BufferedReader bufferread = new BufferedReader(reader);   StreamTokenizer token = new StreamTokenizer(bufferread);     // Use of ordinaryChar() method   // Here we have taken 's' as an ordinary character   token.ordinaryChar('s');     int t;   while ((t = token.nextToken()) != StreamTokenizer.TT_EOF)   {   switch (t)   {   case StreamTokenizer.TT_NUMBER:   System.out.println('Number : ' + token.nval);   break;   case StreamTokenizer.TT_WORD:   System.out.println('Word : ' + token.sval);   break;     }   }   }  }  

Produzione:

Esempio di output' loading='lazy' title=


Struttura delle cartelle:

Strutturacartella' loading='lazy' title=


Articolo successivo  –  Classe Java.io.StreamTokenizer in Java | Insieme 2

Crea quiz