Prezado Rubens,
Veja
se o material abaixo pode lhe ajudar, ou melhor, se ainda pode lhe
ajudar.
Um
abra�o,
Eliseu
Pfaffenseller
Analista de Sistemas Senior.
===========================================================================
1)
Texto com explica��o da classe StringTokenizer.
Separando valores de uma String.
Uma necessidade muito comum entre desenvolvedores � a separa��o de valores contidos em uma String, delimitados por um certo caracter.
Um exemplo seria passar uma String com v�rios IDs atrav�s do par�metro de uma URL, que seria recebida em um servlet e processada como uma array de ints.
A partir do Java 1.4 existe uma forma bem pr�tica de converter um String em uma array de Strings.
Uma necessidade muito comum entre desenvolvedores � a separa��o de valores contidos em uma String, delimitados por um certo caracter.
Um exemplo seria passar uma String com v�rios IDs atrav�s do par�metro de uma URL, que seria recebida em um servlet e processada como uma array de ints.
A partir do Java 1.4 existe uma forma bem pr�tica de converter um String em uma array de Strings.
Basta utilizar o m�todo split, que
aceita uma express�o regular e um limite como par�metros.
Na verdade, o que este m�todo faz �
chamar o m�todo split da classe Pattern, como pode ser visto no c�digo-fonte:
public String[] split(String regex,
int limit)
{
return Pattern.compile(regex).split(this, limit);
}
return Pattern.compile(regex).split(this, limit);
}
Caso voc� ainda n�o tenha a
oportunidade de estar usando o Java 1.4, a solu��o � utilizar a classe
StringTokenizer.
Para converter uma String em uma array de ints, como no exemplo, seria utilizado o seguinte c�digo:
Para converter uma String em uma array de ints, como no exemplo, seria utilizado o seguinte c�digo:
String idString =
"10,20,30,40,50";
StringTokenizer st = new StringTokenizer(idString,",");
int idInt[] = new idInt[st.countTokens()];
int p = 0;
while (st.hasMoreTokens())
StringTokenizer st = new StringTokenizer(idString,",");
int idInt[] = new idInt[st.countTokens()];
int p = 0;
while (st.hasMoreTokens())
{
idInt[p] = Integer.parseInt(st.nextToken());
p++;
}
idInt[p] = Integer.parseInt(st.nextToken());
p++;
}
===========================================================================
2)
Fonte com exemplo de leitura de um arq.texto, utiliza��o da classe
StringTokenizer, e grava��o de uma tabela no BD.
/*Example: Parsing a text file into a database table
In the course of modernizing a record keeping system, you encounter a flat file of data that was created long before the rise of the modern relational database. Rather than type all the data from the flat file into the DBMS, you may want to create a program that reads in the text file, inserting each row into a database table, which has been created to model the original flat file structure.
In the course of modernizing a record keeping system, you encounter a flat file of data that was created long before the rise of the modern relational database. Rather than type all the data from the flat file into the DBMS, you may want to create a program that reads in the text file, inserting each row into a database table, which has been created to model the original flat file structure.
In
this case, we examine a very simple text file. There are only a few rows and
columns, but the principle here can be applied and scaled to larger problems.
There are only a few steps:
Open a
connection to the database.
Loop until the end of the file:
Read a line of text from the flat file.
Parse the line of text into the columns of the table.
Execute a SQL statement to insert the record.
Here is the code of the example program:
*/
import java.io.*;
import java.sql.*;
import java.util.*;
Loop until the end of the file:
Read a line of text from the flat file.
Parse the line of text into the columns of the table.
Execute a SQL statement to insert the record.
Here is the code of the example program:
*/
import java.io.*;
import java.sql.*;
import java.util.*;
public
class TextoParaTabelaBD { //ToDatabaseTable {
private static final String DB = "contacts",
TABLE_NAME = "records",
HOST = "jdbc:mysql://db_lhost:3306/",
ACCOUNT = "account",
PASSWORD = "nevermind",
DRIVER = "org.gjt.mm.mysql.Driver",
FILENAME = "records.txt";
private static final String DB = "contacts",
TABLE_NAME = "records",
HOST = "jdbc:mysql://db_lhost:3306/",
ACCOUNT = "account",
PASSWORD = "nevermind",
DRIVER = "org.gjt.mm.mysql.Driver",
FILENAME = "records.txt";
public static void main (String[] args)
{
try {
try {
// connect to
db
Properties props = new Properties();
props.setProperty("user", ACCOUNT);
props.setProperty("password", PASSWORD);
Properties props = new Properties();
props.setProperty("user", ACCOUNT);
props.setProperty("password", PASSWORD);
Class.forName(DRIVER).newInstance();
Connection con = DriverManager.getConnection(
HOST + DB, props);
Statement stmt = con.createStatement();
Connection con = DriverManager.getConnection(
HOST + DB, props);
Statement stmt = con.createStatement();
// open text
file
BufferedReader in = new BufferedReader(
new FileReader(FILENAME));
BufferedReader in = new BufferedReader(
new FileReader(FILENAME));
// read and parse a
line
String line = in.readLine();
while(line != null) {
String line = in.readLine();
while(line != null) {
StringTokenizer tk = new StringTokenizer(line); //aqui voc� pode testar o
";"
String first = tk.nextToken(),
last = tk.nextToken(),
email = tk.nextToken(),
phone = tk.nextToken();
String first = tk.nextToken(),
last = tk.nextToken(),
email = tk.nextToken(),
phone = tk.nextToken();
//
execute SQL insert
statement
String query = "INSERT INTO " + TABLE_NAME;
query += " VALUES(" + quote(first) + ", ";
query += quote(last) + ", ";
query += quote(email) + ", ";
query += quote(phone) + ");";
stmt.executeQuery(query);
String query = "INSERT INTO " + TABLE_NAME;
query += " VALUES(" + quote(first) + ", ";
query += quote(last) + ", ";
query += quote(email) + ", ";
query += quote(phone) + ");";
stmt.executeQuery(query);
//
prepare to process next
line
line = in.readLine();
}
in.close();
}
line = in.readLine();
}
in.close();
}
catch( Exception e) {
e.printStackTrace();
}
}
e.printStackTrace();
}
}
// protect data with quotes
private static String quote(String include) {
return("\"" + include + "\"");
}
}
private static String quote(String include) {
return("\"" + include + "\"");
}
}
===========================================================
-----Original Message-----
From: Rubens Pereira da Silva [mailto:[EMAIL PROTECTED]
Sent: 06 June, 2003 15:10
To: [EMAIL PROTECTED]
Subject: [java-list] (java lista) - Ler arq. texto delimitado
From: Rubens Pereira da Silva [mailto:[EMAIL PROTECTED]
Sent: 06 June, 2003 15:10
To: [EMAIL PROTECTED]
Subject: [java-list] (java lista) - Ler arq. texto delimitado
Ol� pessoal,Estou precisando de ajuda, sou principiante em java e preciso ler um arquivo texto delimitado por ";" e persistir no banco, qual a melhor forma de fazer? E qual a melhor classe usar?Qualquer dica serve pois tenho urg�ncia, por favor, quem tiver alguma coisa parecida me ajude.Obrigado,Rubens.
Yahoo! Mail
Mais espa�o, mais seguran�a e gratuito: caixa postal de 6MB, antiv�rus, prote��o contra spam.
