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.