Jesus Gregorio Altuve Roa Jesus Gregorio Altuve Roa - 4 months ago 29
Java Question

Java StringTokenizer Error

I'm trying to use the class

to split a character string from a text file, but when I'm running the app, the compiler prints in the Netbeans console the words that I'm splitting but also shows an exception.

This is my code:

package Calqfunny;

import java.util.StringTokenizer;
import javax.swing.JOptionPane;

public class Files {

public String direccion;

public Files(){

direccion = " ";

public Files(String direccion){

this.direccion = direccion;

public String leerTxt(String direccion){

String auxiliar = " ";


BufferedReader br = new BufferedReader(new FileReader(direccion));
String temp = " "; //Aqui guardamos el texto del archivo temporalmente
String banana; //aqui almacenamos

while((banana = br.readLine())!=null){
//se realiza el ciclo mientras que el archivo tenga datos.

temp = temp + banana;

auxiliar = temp;

}catch(Exception e){

JOptionPane.showMessageDialog(null,"\"¿Cómo vas a pedir un archivo que no existe? boludo :v\"");


String nombre = null, apellido = null, edad = null, bday = null;
StringTokenizer tokens = new StringTokenizer (auxiliar, ";");

System.out.println("Nombre\tApellido Edad\tFecha de Nac.");

nombre = tokens.nextToken();
apellido = tokens.nextToken();
edad = tokens.nextToken();
bday = tokens.nextToken();



return auxiliar;

This is the output from my app

Nombre Apellido Edad Fecha de Nac.
David Villa 31 1985
Andrea Pirlo 36 1980
Lionel Messi 29 1987
Tomas Rincon 27 1989

And this is the exception that the compiler throws

Exception in thread "main" java.util.NoSuchElementException

at java.util.StringTokenizer.nextToken(

at Calqfunny.Files.leerTxt(

at Calqfunny.Mein.main(

C:\Documents and Settings\Goyo\Configuración local\Datos de
programa\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned:1

BUILD FAILED (total time: 0 seconds)

What can I do to solve it?


Your while loop is testing if the StringTokenizer has ONE more token. But then you are reading FOUR more tokens. This is going to crash when the number of tokens is not divisible by four.

What you can safely do is:

StringTokenizer tokens = new StringTokenizer(auxiliar, ";");

    token = tokens.nextToken();