Java - StringTokenizer, campos vacios.

 
Vista:

StringTokenizer, campos vacios.

Publicado por MaLa (1 intervención) el 07/04/2008 17:27:47
Hola a todos,

Me he encontrado con un problemita en Java que me gustaria me ayudaran a solucionar.

Estoy haciendo una aplicación que lee datos de un archivo de texto y los inserta en una tabla MySQL, la estructura del archivo está bien definida separando cada campo por el caracter "|" y las filas por el fin de linea tradicional.

El problema se me presenta cuando algun campo del archivo viene vacío, la clase tokenizer no toma en cuenta el campo y hace que las columnas de la tabla no correspondan, por lo que me da un error y se interrumpe la ejecucuón.

Ejemplo: Pedro|Peres|12333444|Caracas|2523344|ofi
Juan|Gomez|14123321|Valencia||ofi2
En este caso el espacio entre || (correspondiente a Juan) debe ser tomado en cuenta como vacio pero no lo reconoce ya que estan los separadores juntos. Alguien sabe como filtrar esta condicion?
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:StringTokenizer, campos vacios.

Publicado por mario (622 intervenciones) el 07/04/2008 18:01:43
Es un Bug que Sun no quiso corregir aki un argumento de ellos precisamente salio por eso te las bases de datos

StringTokenizer is a very simple String scanner. It does not do "everything
for everyone", and probably never will. In the most common usage pattern, a String containing all of the whitespace characters is provided as delim, and the user gets back a token for ever "word" in the file.

It is reasonably straightforward to build the functionality you want on
top of StringTokenizer:

StringTokenizer st = new StringTokenizer(args[0], " ", true);
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (s.equals(" ")) {
System.out.println("Line: ''");
} else {
System.out.println("Line: '" + s + "'");
if (st.hasMoreTokens())
st.nextToken(); // Skip ' ' separator
}
}

Esta es una posible solucion con su main checate el codigo, espero t sea de utuilidad:

/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Boston, MA 02111.
* */
package org.neos.test;

import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Vector;

public class StringTokenizerStrict extends StringTokenizer
{
protected String delim = " f";
protected String storedToken = null;
protected boolean lastWasToken = true;
protected Vector tokens = null;
protected int currentToken = 0;
protected boolean returnTokens = false;
protected boolean internal = false;
protected synchronized void buildInternal()
{
tokens = new Vector();
try {
while ( true ) {
tokens.addElement(nextTokenInternal());
}
} catch ( NoSuchElementException e ) {
tokens.trimToSize();
currentToken = 0;
lastWasToken = true;
storedToken = null;
return;
}
}
public StringTokenizerStrict(String s)
{
this(s," f");
}
public StringTokenizerStrict(String s,String delim)
{
this(s,delim,false);
}
public StringTokenizerStrict(String s,String delim,boolean returnTokens)
{
super (s,delim,true);
this.delim = delim;
this.returnTokens = returnTokens;
buildInternal();
}
public int countTokens()
{
return tokens.size() - currentToken;
}
public boolean hasMoreElements()
{
return ( countTokens() != 0 );
}
public Object nextElement()
{
return nextToken();
}

public String nextToken(String delim)
{
if ( delim.equals(this.delim) )
return nextToken();
this.delim = delim;
buildInternal();
return nextToken();
}
public String nextToken()
{
if ( internal )
return super.nextToken();
return (String) tokens.elementAt(currentToken++);
}
protected String nextTokenInternal()
{
try {
internal = true;
if ( storedToken != null ) {
String s = storedToken;
storedToken = null;
return s;
}
String s = super.nextToken(delim);
if ( s.length() == 1 )
if ( delim.indexOf(s) != -1 )
if ( lastWasToken ) {
if ( returnTokens )
storedToken = s;
return "";
} else {
lastWasToken = true;
if ( returnTokens )
return s;
else
return nextTokenInternal();
}
lastWasToken = false;
return s;
} finally {
internal = false;
}
}
public boolean hasMoreTokens()
{
return hasMoreElements();
}

public static void main(String args[]) {
StringTokenizerStrict tokenizer= new
StringTokenizerStrict("Pedro|Peres|12333444|Caracas|2523344|ofiJuan|Gomez|14123321|Valencia||ofi2","|");

while(tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar