RE: [java-list] Sou mais um novato!!!
Roberto, Dê uma olhada em http://www.acm.org/crossroads/columns/ovp/march2001.html. Lá você encontra um exemplo de leitura de arquivo texto e gravação de uma tabela, etc. Acredito que ajude. Eliseu Pfaffenseller Analista de Sistemas Senior. == Fonte com exemplo de leitura de um arq.texto, utilização da classe StringTokenizer, e gravação deuma tabela no BD. Origem: www.acm.org/crossroads/columns/ovp/march2001.html /*Example: Parsing a text file into a database tableIn 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.*; 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"; public static void main (String[] args) { try { // connect to db 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(); // open text file BufferedReader in = new BufferedReader( new FileReader(FILENAME)); // read and parse a line 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(); // 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); // prepare to process next line line = in.readLine(); } in.close(); } catch( Exception e) { e.printStackTrace(); } } // protect data with quotes private static String quote(String include) { return("\"" + include + "\""); }} === -Original Message-From: Roberto da Silva [mailto:[EMAIL PROTECTED]Sent: 01 July, 2003 09:16To: [EMAIL PROTECTED]Subject: [java-list] Sou mais um novato!!! Moçada, procurei pela Internet mas não achei o que queria, alguém poderia me enviar um código bem simples, de como abrir um arquivo, lerestou usando o Java.io mas ainda não consegui entender direito o Java então estou domando porrada dele Obrigado Roberto da Silva
RE: [java-list] INSERT EM UM TABELA QUE POSSUI CAMPO DATE SEM USAR O TO_DATE DO ORACLE
Rubens, Já fiz INSERT em tabela Oracle, porém utilizando o TO_DATE mesmo. Veja abaixo, um "pedaço" do código, onde faço isso: === ... String dtInicial = ("01/01/2002"); String gruContagem = (line.substring( 17, 18)); String codProduto = (line.substring( 28, 42)); String unMedida = (line.substring( 74, 77)); String idCCusteio = (line.substring( 58, 60)); String cCusteio = (line.substring( 60, 70)); String qtdeProduto = (line.substring( 77, 88) + "." + line.substring( 88, 94)); // Mount query to execute SQL insert statement String query; query = "INSERT INTO " + "ICMS_SALDO_INICIAL" + " VALUES("; query += "TO_DATE('"+dtInicial+"','DD/MM/')" + ", "; query += quote(gruContagem) + ", "; query += quote(codProduto) + ", "; query += quote(unMedida) + ", "; query += quote(idCCusteio) + ", "; query += quote(cCusteio) + ", "; query += quote(qtdeProduto) + ") "; try { // execute SQL insert statement qtde51 += 1; if ((qtde51 % 1000) == 0) System.out.println(qtdeLi + " = " + query); stmt.executeQuery(query); } catch(SQLException ex) { pw.println(qtdeLi+" "+query); pw.println(ex.getMessage()); pw.println(); } ...=== Desculpe seisso em nadapodeajudá-lo... Um abraço, Eliseu Pfaffenseller Analista de Sistemas Senior. -Original Message-From: Rubens Pereira da Silva [mailto:[EMAIL PROTECTED]Sent: 01 July, 2003 17:27To: [EMAIL PROTECTED]Subject: [java-list] INSERT EM UM TABELA QUE POSSUI CAMPO DATE SEM USAR O TO_DATE DO ORACLE Boa tarde, Pessoa estou precisando de ajunda, é o seguinte: Estou utilizando o banco de dados oracle e possuo um tabela com 3 campos e estou tentando fazer um INSERT nessa tabela só que, um campo possui o datatype DATE no meu programa java tenho uma variavél do tipo String dt = ("16/05/2002") já tentei de varias formas passar essa variavél para instrução INSERTutilizei as classes java.util.Date, java.sql.Date e java.sql.Timestamp mas não obtive sucesso,não sei se estou utlizando as classes acima da maneira correca so iniciante em JAVA, eu não posso usar o to_date do oracle alguem poderia me ajudar como eu devo fazer o INSERT EM UM TABELA QUE POSSUI CAMPO DATE SEM USAR O TO_DATE DO ORACLE. Muito obrigado, Rubens. Yahoo! Mail Mais espaço, mais segurança e gratuito: caixa postal de 6MB, antivírus, proteção contra spam.
RE: [java-list] swing
Prezado Osmar, Veja se voc no encontra a resposta no tutorialabaixo. (Fonte: http://www.grandt.com/sbe/Part II. The Basics 11.Text Components and Undo) Um abrao, Eliseu Pfaffenseller Analista de Sistemas Senior. -Original Message-From: Omar Leite [mailto:[EMAIL PROTECTED]Sent: 12 June, 2003 18:13To: [EMAIL PROTECTED]Subject: [java-list] swing Pessoal, por favor Gostaria de saber como se insere linha a linha num jTextArea, jTextPane ou jEditorPane grato.
RE: [java-list] (java lista) - Ler arq. texto delimitado
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. Origem:http://www.java.blogger.com.br/2002_12_08_archive.html 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. 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); } 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: String idString = "10,20,30,40,50";StringTokenizer st = new StringTokenizer(idString,","); int idInt[] = new idInt[st.countTokens()]; int p = 0; while (st.hasMoreTokens()) { 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 deuma tabela no BD. Origem: www.acm.org/crossroads/columns/ovp/march2001.html /*Example: Parsing a text file into a database tableIn 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.*; 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"; public static void main (String[] args) { try { // connect to db 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(); // open text file BufferedReader in = new BufferedReader( new FileReader(FILENAME)); // read and parse a line 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(); // 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); // prepare to process next line line = in.readLine(); } in.close(); } catch( Exception e) { e.printStackTrace(); } } // protect data with quotes private static String quote(String include) { return("\"" + include + "\""); }} === -Original Message-From: Rubens Pereira da Silva [mailto:[EMAIL PROTECTED]Sent: 06 June, 2003 15:10To: [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.
RE: [java-list] Conversão de valor númerico para valor em extenso
Prezado Andrew, Não sei se é isso que você precisa/quer, mas lá vai. Fonte divulgado por Mauro Martini, em 29/05/2003: = //package converter; /** * Title: * Description: * Copyright:Copyright (c) 2001 * Company: Despodata * * @author * @created9 de Maio de 2003 * @since 9 de Maio de 2003 * @version1.0 */ /** * Usage of the class: * to create an instance of the class and by this instance * using SetNumber(or passing the number to the constructor) and GetResult methods * * @author Mauro * @created9 de Maio de 2003 * @since 9 de Maio de 2003 */ public class Extenso { /** Description of the Field */ private double num; //The number that is going to be converted /** Description of the Field */ private String s; //The String that is going to be returned /** Description of the Field */ private int maxlen; //our result string's wrap limit.. /** Description of the Field */ private int cut_point; /** Description of the Field */ private boolean centavo = false; //Constructors /**Construtor para o objeto Extenso */ public Extenso() { } /** *Construtor para o objeto Extenso * * @param num_ Description of the Parameter * @param maxlen_ Description of the Parameter */ public Extenso(double num_, int maxlen_) { setNumber(num_, maxlen_); } /** * To set the number to be converted * * @param num_ Description of the Parameter * @param maxlen_ Description of the Parameter */ public void setNumber(double num_, int maxlen_) { num = num_; s = new String(); maxlen = maxlen_; Extenso(); } /** The function that makes the convertion */ private void Extenso() { String nome[] = { um bi-lhão, bi-lhões, um mi-lhão, mi-lhões}; long n = (long)num; long mil_milhoes; long milhoes; long milhares; long unidades; long centavos; char numero[]; double frac = num - n; int nl; int rp; int last; int p; int len; if (num == 0) { s += zero; return; } mil_milhoes = (n - n % 10) / 10; n -= mil_milhoes * 10; milhoes = (n - n % 100) / 100; n -= milhoes * 100; milhares = (n - n % 1000) / 1000; n -= milhares * 1000; unidades = n; centavos = (long)(frac * 100); if ((long)(frac * 1000 % 10) 5) { centavos++; } // s = \0; //s[0] = '\0' ; //?? if (mil_milhoes 0) { if (mil_milhoes == 1) { s += nome[0]; } else { s += numero(mil_milhoes); s += nome[1]; } if ((unidades == 0) ((milhares == 0) (milhoes 0))) { s += e ; } else if ((unidades != 0) || ((milhares != 0) || (milhoes != 0))) { s += , ; } } if (milhoes 0) { if (milhoes == 1) { s += nome[2]; } else { s += numero(milhoes); s += nome[3]; } if ((unidades == 0) (milhares 0)) { s += e ; } else if ((unidades != 0) || (milhares != 0)) { s += , ; } } if (milhares 0) { if (milhares != 1) { s += numero(milhares); } s += mil; if (unidades 0) { if ((milhares 100) (unidades 100)) { s += , ; } else if (((unidades % 100) != 0) || ((unidades % 100 == 0) (milhares 10))) { s += e ; } else { s += ; } } } s += numero(unidades); if (num 0) { s += ((long)num == 1L) ? real : reais; } if (centavos != 0) { if (n != 0) { centavo = true; } s += e ; s += numero(centavos); s += (centavos==1) ? cen-ta-vo : cen-ta-vos; } len = s.length(); StringBuffer sar = new StringBuffer(s); StringBuffer l = new StringBuffer(); last = 0; rp = 0; nl = 1; for (p = 0; p len; ++p) { if (sar.charAt(p) != '-') { rp++; } if (rp maxlen) { if (sar.charAt(last) == ' ') { sar.replace(last, last + 1, \n); } else { sar.insert(last + 1, '\n'); } rp -= maxlen; nl++; } if ((sar.charAt(p) == ' ') || (sar.charAt(p) == '-')) { last = p; } } //for rp = 0; len = sar.length(); for (p = 0; p len; ++p) { if (!((sar.charAt(p) == '-') (sar.charAt(p + 1) != '\n'))) { l.insert(rp++, sar.charAt(p)); } } //for s = l.toString(); } /** * Return the written form of the number * * @return... */ public String getResult() { String temp; if (s == null) { return Number is not set!; } temp = s; s = null; return temp; } /** * Return the numbers between 0-999 in written form * * @param n Description of the Parameter * @return... */ private
RE: [java-list] Re: Numero por extenso
Prezado Luiz Antonio, Fonte divulgado por Mauro Martini, em 29/05/2003: = //package converter; /** * Title: * Description: * Copyright:Copyright (c) 2001 * Company: Despodata * * @author * @created9 de Maio de 2003 * @since 9 de Maio de 2003 * @version1.0 */ /** * Usage of the class: * to create an instance of the class and by this instance * using SetNumber(or passing the number to the constructor) and GetResult methods * * @author Mauro * @created9 de Maio de 2003 * @since 9 de Maio de 2003 */ public class Extenso { /** Description of the Field */ private double num; //The number that is going to be converted /** Description of the Field */ private String s; //The String that is going to be returned /** Description of the Field */ private int maxlen; //our result string's wrap limit.. /** Description of the Field */ private int cut_point; /** Description of the Field */ private boolean centavo = false; //Constructors /**Construtor para o objeto Extenso */ public Extenso() { } /** *Construtor para o objeto Extenso * * @param num_ Description of the Parameter * @param maxlen_ Description of the Parameter */ public Extenso(double num_, int maxlen_) { setNumber(num_, maxlen_); } /** * To set the number to be converted * * @param num_ Description of the Parameter * @param maxlen_ Description of the Parameter */ public void setNumber(double num_, int maxlen_) { num = num_; s = new String(); maxlen = maxlen_; Extenso(); } /** The function that makes the convertion */ private void Extenso() { String nome[] = { um bi-lhão, bi-lhões, um mi-lhão, mi-lhões}; long n = (long)num; long mil_milhoes; long milhoes; long milhares; long unidades; long centavos; char numero[]; double frac = num - n; int nl; int rp; int last; int p; int len; if (num == 0) { s += zero; return; } mil_milhoes = (n - n % 10) / 10; n -= mil_milhoes * 10; milhoes = (n - n % 100) / 100; n -= milhoes * 100; milhares = (n - n % 1000) / 1000; n -= milhares * 1000; unidades = n; centavos = (long)(frac * 100); if ((long)(frac * 1000 % 10) 5) { centavos++; } // s = \0; //s[0] = '\0' ; //?? if (mil_milhoes 0) { if (mil_milhoes == 1) { s += nome[0]; } else { s += numero(mil_milhoes); s += nome[1]; } if ((unidades == 0) ((milhares == 0) (milhoes 0))) { s += e ; } else if ((unidades != 0) || ((milhares != 0) || (milhoes != 0))) { s += , ; } } if (milhoes 0) { if (milhoes == 1) { s += nome[2]; } else { s += numero(milhoes); s += nome[3]; } if ((unidades == 0) (milhares 0)) { s += e ; } else if ((unidades != 0) || (milhares != 0)) { s += , ; } } if (milhares 0) { if (milhares != 1) { s += numero(milhares); } s += mil; if (unidades 0) { if ((milhares 100) (unidades 100)) { s += , ; } else if (((unidades % 100) != 0) || ((unidades % 100 == 0) (milhares 10))) { s += e ; } else { s += ; } } } s += numero(unidades); if (num 0) { s += ((long)num == 1L) ? real : reais; } if (centavos != 0) { if (n != 0) { centavo = true; } s += e ; s += numero(centavos); s += (centavos==1) ? cen-ta-vo : cen-ta-vos; } len = s.length(); StringBuffer sar = new StringBuffer(s); StringBuffer l = new StringBuffer(); last = 0; rp = 0; nl = 1; for (p = 0; p len; ++p) { if (sar.charAt(p) != '-') { rp++; } if (rp maxlen) { if (sar.charAt(last) == ' ') { sar.replace(last, last + 1, \n); } else { sar.insert(last + 1, '\n'); } rp -= maxlen; nl++; } if ((sar.charAt(p) == ' ') || (sar.charAt(p) == '-')) { last = p; } } //for rp = 0; len = sar.length(); for (p = 0; p len; ++p) { if (!((sar.charAt(p) == '-') (sar.charAt(p + 1) != '\n'))) { l.insert(rp++, sar.charAt(p)); } } //for s = l.toString(); } /** * Return the written form of the number * * @return... */ public String getResult() { String temp; if (s == null) { return Number is not set!; } temp = s; s = null; return temp; } /** * Return the numbers between 0-999 in written form * * @param n Description of the Parameter * @return... */ private String numero(long n) { int flag; String
RE: [java-list] montar um arquivo word (doc)
Prezado Sergio, Veja se no site http://www.grandt.com/sbe/ Part III. Advanced Topics 20. Constructing a Word Processor.Talvez possa lhe ajudar. Segue abaixo, fonte de umprograminha simples, que gera um texto comum (sem elementos gráficos) e, no final executa o word abrindo o arquivo gerado. Um abraço, Eliseu Pfaffenseller/Analista de Sistemas Senior. //Exemplo de geração de um arquivo texto, abrindo-o ao final no Word import java.sql.*;import java.io.*;import java.text.*;import javax.swing.*; public class GeraTexto { public static void main(java.lang.String[] args) { System.out.println("INICIO"); // Arquivo Texto de Saida PrintWriter pw = null; String fw = "c:\\temp\\Texto.doc"; try { pw = new PrintWriter(new FileWriter(fw)); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } System.out.println("Gerando Arquivo " + fw); pw.println(" "); pw.println("Isto é apenas um teste de geração de um arquivo texto"); pw.println("="); for (int i=1;i=20;++i) //aqui entra um loop qualquer, seja processando tabela banco, etc. { StringBuffer buf = new StringBuffer(" "); NumberFormat fmt = NumberFormat.getInstance(); fmt.setMinimumIntegerDigits(3); fmt.setMaximumIntegerDigits(3); buf.insert(0, fmt.format(i)); buf.insert(3, "| "); buf.insert(5, "Pedro da Silva "); buf.insert(41, "| "); buf.insert(43, "Pedreiro "); pw.println(buf + "|"); } pw.println("="); pw.println("Fim do arquivo texto"); //pw.println("Fim do Texto"); pw.close(); System.out.println("FIM"); //Agora o procedimento para executar o Word, abrindo o arquivo gerado: Runtime rt = Runtime.getRuntime(); String[] callAndArgs = { "C:\\Program Files\\Microsoft Office\\Office\\WinWord.exe", "c:\\TEMP\\Texto.doc" }; try { Process child = rt.exec(callAndArgs); child.waitFor(); System.out.println("Process exit code is: " + child.exitValue()); } catch(java.io.IOException e) { System.err.println("IOException starting process!"); } catch(InterruptedException e) { System.err.println("Interrupted waiting for process!"); } }}//Fim do Fonte. -Original Message-From: Sergio Cintra [mailto:[EMAIL PROTECTED]Sent: 11 June, 2003 10:37To: Sou Java Java-listSubject: [java-list] montar um arquivo word (doc) Pessoal, Preciso da ajuda de vocês! Alguém da lista sabe como montar um arquivo word (doc) a partir de uma classe java, ou então com qualquer outra tecnologia que eu possa acionar através de uma classe? []'s Sergio Cintra Yahoo! Mail O melhor e-mail gratuito da internet: 6MB de espaço, antivírus, acesso POP3, filtro contra spam.
RE: [java-list] Dvida cruel
A Classe String === Fonte: http://www.mycgiserver.com/servlet/delacerda.CertificacaoTopicoNove Em Java voc tem duas classes para encapsular string de characters chamadas String e StringBuffer. Se voc cria uma instncia de classe String , no existe maneira de mudar o valor encapsulado i.e. chamado imutabilidade, ento strings so imutveis. Construindo Strings: String s = Testing String; String s1 = new String(Testing String); A diferena entre as duas formas de construo string que , o lugar onde estas strings so disponveis. String s = Testing String; Qaundo voc cria o objeto String no formato abaixo ento o objeto String est disponvel dentro do pool de string literals. Se a mesma string j existe no pool de strings ento a antiga string vai ser substituida pela nova. String s1 = new String(Testing String); Quando voc constroi a String chamando a palavra chave new ento o objeto String vai ser criado em tempo de execuo e no vai existir no pool de strings. Para colocar esta string encapsulada dentro do pool chame o mtodo intern() . Testando String Equality Exemplo: String s = Testing String; String s1 = new String(Testing String); Para testar s e s1 use o mtodo equals() s.equals(s1); Se voc no conhece quando os dois tipos referenciados pertencem ao mesmo objeto ou objetos diferentes e voc realmente no quer saber , ento utilize o mtodo equals() . Exemplo: String s = Testing String ; String s1 = Testing String; Se duas referencias referem para o mesmo objeto ento use == . Para testar s e s1 use == s = s1; Existem alguns mtodos da classe String que podem ser interessantes. Mtodos da Classe String: concat() equals() equalsIgnoreCase() length() substring() toLowerCase() toUpperCase() trim() Exemplo: public class TestString { public static void main(String args[]) { String s = Hello; String s1 = how; s1.append(is going); String s2 = s.concat(s1.concat( are you)); String s3 = hello; if (s3.equalsIgnoreCase(s)) System.out.println(s2); } } Sada: Hello how are you Aqui o mtodo append() no um mtod da classe String mas mesmo assim ele compila e d a voc a sada abaixo. Cuidado sobre este tipo de exemplos , voc pode ter questes como estas no seu exame real. Algumas vezes no exame real voc pode esperar questes comparando dois construtores de strings com classes String e StringBuffer . StringBuffer Class: Os construtores de strings com esta classe podem ser modificados. Exemplo: public class TestBString { public static void main(String args[]) { StringBuffer s = new StringBuffer(Hello); String s1 = Hello; if (s1.equals(s)) System.out.println(s); } } O exemplo acima escreve nada na sada do console. Alguns mtodos da classe StringBuffer: Mtodos StringBuffer : append() insert() reverse() setCharAt() setLength() Fonte: http://www.mycgiserver.com/servlet/delacerda.CertificacaoTopicoNove Eliseu Pfaffenseller Analista de Sistemas Senior -Original Message- From: Alexandro Strack [mailto:[EMAIL PROTECTED] Sent: 02 June, 2003 16:06 To: [EMAIL PROTECTED] Subject: Re: [java-list] Dvida cruel Caro Rodrigo, Se voc j sabe da imutabilidade das Strings ento s lhe falta o fato da passagem de parmetros der por valor e no por referncia. Ah, s mais um detalhe, a varivel y no est vazia mais sim com o contedo teste- . Um abrao, Alexandro Strack - Original Message - From: Rodrigo Alvares de Souza [EMAIL PROTECTED] To: [EMAIL PROTECTED] Sent: Friday, May 30, 2003 10:31 AM Subject: [java-list] Dvida cruel Alguem saberia me dizer pq qdo eu imprimo a variavel y, ela est vazia ? Eu sei que tem a ver com a imutabilidade das Strings, mas queria uma resposta que me convencesse :-) public class teste1 { public teste1() {} public static void main(String[] args) { teste1 t = new teste1(); String y = new String(teste - ); int z = 10; System.out.println(t.x(y,z)); System.out.println(y); } private String x (String str1,int z) { str1 = str1.concat( ok ) ; z = 2003; return str1; } } Obrigado. Atenciosamente, Paulo Henrique C. Zanchettin Scopus Tecnologia S/A ( 55-11-3909-3561 * [EMAIL PROTECTED] -- LISTA SOUJAVA http://www.soujava.org.br -
RE: [java-list] Impresso em java
Luciani, D uma olhada no site abaixo. http://www.grandt.com/sbe/ = Veja o chapter 22 (Printing), do livro Swing... Veja tambm: http://java.sun.com/printing/ http://www.mundooo.com.br/php/modules.php?name=Newsfile=articlesid=529 http://www.javaworld.com/javaworld/jw-10-2000/jw-1020-print.html http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20330121.html http://java.sun.com/products/java-media/2D/forDevelopers/sdk12print.html Eliseu Pfaffenseller Analista de Sistemas Senior -Original Message-From: Luciani Pizato [mailto:[EMAIL PROTECTED]Sent: 21 May, 2003 09:49To: [EMAIL PROTECTED]Subject: [java-list] Impresso em java Ol pessoal, Estou com um problema, preciso encontrar uma forma de fazer impresso em java. Criei um pequeno editor de textos, e no menu imprimir, preciso criar uma funo que imprima o arquivo que est na tela. Como fao isso... Preciso de ajuda Obrigada... Luciani Pizato[EMAIL PROTECTED]
RE: [java-list] String e NULL
Everton, Tente isso: if (str == null) ... Eliseu Pfaffenseller Analista de Sistemas Senior -Original Message- From: Everton - Casa [mailto:[EMAIL PROTECTED] Sent: 16 May, 2003 09:18 To: [EMAIL PROTECTED] Subject: [java-list] String e NULL Caros colegas, além do método length() de String (retornando 0), existe uma maneira de verificar se uma String é Nula ? Por exemplo String.isNull() ? Grato e abraços Everton --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.476 / Virus Database: 273 - Release Date: 24/4/2003 -- LISTA SOUJAVA http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] - -- LISTA SOUJAVA http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] -
RE: [java-list] EXECUTAR .EXE APARTIR DE UMA CLASSE!
Prezado José Carlos, Se pode lhe ajudar, aí vai um exemplo para chamar o WORD, já informando o ARQUIVO.DOC(opcional) que ele deve abrir: == Runtime rt = Runtime.getRuntime(); String[] callAndArgs = { C:\\Program Files\\Microsoft Office\\Office\\WinWord.exe, U:\\ARQUIVO.DOC }; try { Process child = rt.exec(callAndArgs); child.waitFor(); System.out.println(Process exit code is: + child.exitValue()); } catch(java.io.IOException e) { System.err.println(IOException starting process!); } catch(InterruptedException e) { System.err.println(Interrupted waiting for process!); } == Um abraço, Eliseu Pfaffenseller Analista de Sistemas Senior. -Original Message- From: José Carlos Lopes de Barros [mailto:[EMAIL PROTECTED] Sent: 19 May, 2003 15:04 To: '[EMAIL PROTECTED]' Subject: [java-list] EXECUTAR .EXE APARTIR DE UMA CLASSE! Pessoal, sei que isso já saiu na lista mas peço que enviem como posso executar um .exe apartir de uma classe, me lembro que é com a classe Runtime mas não sei como fazer isso. Agradeço desde ja´.!!! SPARC -- LISTA SOUJAVA http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] - -- LISTA SOUJAVA http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] -
RE: [java-list] Ferramenta p/ Editar arquivos *.java
Tente o SunONE (é free e é muito bom): http://wwws.sun.com/software/sundev/jde/buy/index.html Sun[tm] ONE Studio 4 update 1 Community Edition Eliseu Pfaffenseller Analista de Sistemas Senior -Original Message-From: IGMail Marcelo Conceição - II [mailto:[EMAIL PROTECTED]Sent: 27 March, 2003 09:57To: [EMAIL PROTECTED]Subject: [java-list] Ferramenta p/ Editar arquivos *.javaImportance: High Olá Pessoal, tudo bem... Estou com uma dúvida em relação a uma ferramenta(s) p/ se editar arquivos .java. Estou usando o JCreator LE mas ele não está me agradando, então gostaria de usar uma outra ferramenta porque estou precisando urgente disto. Se alguém puder me ajudar desde já agradeço... até mais pessoal =) Marcelo Ap. da Conceição- 21 anos/ Universitário HP Web: www.as2004.hpg.com.br HP Web: www.bandagmpiracicaba.hpg.com.br e-mail: [EMAIL PROTECTED]ouvia SMS(celular) que é [EMAIL PROTECTED] MSN Messenger: [EMAIL PROTECTED] Fone: +55 (19) 3425-3704 Celular: +55 (19) 9753-1457 Comercial: +55 (19) 3403-9628 Piracicaba/SP - Brazil.
RE: [java-list] Formatação decimal de uma String
Mr.AsaDelta, Não sei se é bem isso que você quer, mas aí vai um exemplo de formatação. O método transform está preparado para receber double(com máscara e sem máscara), mas você pode criar as variações que quiser. Eliseu Pfaffenseller Analista de Sistemas. //INÍCIO DO FONTE: import java.text.*;class JFNumber{ //==\\ // transform function: // Put number to the Brazilian/English Format (decimal point is comma) // and format to the optional informed mask public static String transform(double num) { return(transform(num, null)); } public static String transform(double num, String mask) { DecimalFormat df = new DecimalFormat(); DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setCurrencySymbol("R$"); dfs.setGroupingSeparator('.'); dfs.setDecimalSeparator(','); df.setDecimalFormatSymbols(dfs); if(mask != null) df.applyPattern(mask); return(df.format(num)); } //==\\}//TESTE:public class Teste{ public static void main(java.lang.String[] args) { System.out.println(JFNumber.transform(123456.78,"###,##0.00")); System.out.println(JFNumber.transform(123456.78)); System.out.println(JFNumber.transform(0.12,"###,##0.00")); System.out.println(JFNumber.transform(0.12,"R$ ###,##0.00")); System.out.println(JFNumber.transform(456.78,"000,000.00")); System.out.println(JFNumber.transform(3456.78,"000,000.00")); System.out.println(JFNumber.transform(3456.78,"00.00")); }}//FIM DO FONTE -Original Message-From: asadelta java [mailto:[EMAIL PROTECTED]Sent: 11 March, 2003 15:03To: [EMAIL PROTECTED]Subject: [java-list] Formatação decimal de uma String Olá, como faço para fazer um formatação decimal de uma string obtida do BD? P.ex. Recebi as Strings str1 = "123"; // o resultado deveria ser 1,23 decimal str2 = "123456" // o resultado deveria ser 1.234,56 decimal Na API do Java existe alguma alternativa fácil ou teria que fazer na unha? Obrigado. Busca Yahoo! O serviço de busca mais completo da Internet. O que você pensar o Yahoo! encontra.
RE: [java-list] JAVA e mySQL
Luciano, Veja o livro abaixo. Achei-o muito bom e baratíssimo. Eliseu Pfaffenseller Analista de Sistemas. http://www.submarino.com.br/books_productdetails.asp?Query=ProductPageProdTypeId=1ProdId=181195ST=SE Tudo o que Você Queria Saber Sobre JSP FERNANDO ANSELMO Disponiblidade: Em EstoqueEntrega: 1 dia útil para Grande São Paulo* Lista:Submarino:Economize: R$R$R$ 39,0031,907,10 Sinopse:Este livro está dividido em cinco capítulos para facilitar seu aprendizado em Java Server Pages. O primeiro capítulo irá lhe ajudar a instalar e configurar o servidor que utilizaremos e a colocar o JSP rodando no ambiente Windows, acessando o banco MySQL. O segundo trará a descrição de um dos melhores editores que conheço - tanto de Java, quanto de HTML e JSP - porém, raramente vemos qualquer documentação sobre o assunto, por isso que decidi mostrar todas as minúcias deste, além de dar algumas dicas sobre a programação Java. No terceiro capítulo, que acredito ser o maior do livro, iremos desenvolver um sistema completo passo a passo em JSP. No quarto capítulo, iremos nos deliciar com os feijões e desvendaremos os mistérios dos Beans, como criá-los, qual sua utilidade e para que servem. E, no quinto e último capítulo, falarei de alguns macetes e descobertas que fiz utilizando o JSP, quando trataremos do assunto Tags Personalizadas. Completando este, teremos um Apêndice que conterá os comandos básicos com o JSP, outro para comandos do MySQL e um último para os comandos em linguagem HTML.Este livro é para usuários de Windows. Ranking: Prazo de Entrega: *(válido para compras com cartão de crédito aprovado na 1ª tentativa e efetuadas até às 20 horas)1 dia útil: Cidade de São Paulo e ABCD.2 dias úteis: Cidades: Rio de Janeiro, Belo Horizonte, Curitiba, Porto Alegre, Goiânia, Salvador, Brasília, Fortaleza, Recife e Olinda.Até 5 dias úteis: Outras localidades. Dados Técnicos: Editora:Visual BooksISBN:8575020943Ano:2002Edição: 1Número de páginas: 192Acabamento: Brochura Formato: Médio -Original Message-From: Luciano Cordeiro [mailto:[EMAIL PROTECTED]Sent: 12 March, 2003 09:03To: [EMAIL PROTECTED]; [EMAIL PROTECTED]Subject: [java-list] JAVA e mySQL Olá Henderson ! Trabalho aqui na Unimed Maceió, e estou querendo mudar as tecnologias utilizadas no nosso site, prá JAVA com mySQL. Se você pudesse também me enviar esse capítulo do seu livro, agradeceria ! Atenciosamente , Luciano CordeiroAnalista de Sistemas[EMAIL PROTECTED][EMAIL PROTECTED][EMAIL PROTECTED]ICQ#: 49154876 - Original Message - From: "Henderson" [EMAIL PROTECTED] To: [EMAIL PROTECTED]; "java-list" [EMAIL PROTECTED] Sent: Thursday, November 21, 2002 3:49 PM Subject: [java-list] MySQL e Java Thyago, estou escrevendo um livro sobre Java e MySQL. No momento só tenho pronto o capítulo de MySQL mas se vc quiser me avise que mando.Sds.Henderson MacedoDepartamento de SoftwareDRAFT Automação Industrial -
RE: [java-list] Re:[java-list] Banco OO
Sr.Herval, Esta eu não entendi(???). Não conheço o PostgreeSQL, mas tirei o texto abaixo da página http://pgsqlbr.querencialivre.rs.gov.br/ "O PostgreSQL é um sofisticado sistema de gerenciamento de banco de dados relacional e orientado a objetos, suportando quase todas as contruções SQL, incluindo subseleções, transações, tipos definidos pelo usuário e funções . Ele é o mais avançado banco de dados de código livre disponível .Atualmente está disponível seu código fonte, além de binários pré-compilados em diversas plataformas ." Quem está errado? Eliseu Pfaffenseller/Analista de Sistemas. -Original Message-From: Herval Freire [mailto:[EMAIL PROTECTED]Sent: 05 March, 2003 10:05To: [EMAIL PROTECTED]Subject: Re: [java-list] Re:[java-list] Banco OO Pessoal!Nem o mySQL nem o PostgreSQL sao bancos Orientados a Objetos...Não vamos confundir as coisas..[]sAt 08:15 25/2/2003 -0300, you wrote: olá o mysql é free.O site dele é esse:http://www.mysql.com Alguem conhece algum Banco de Dados orientado a Objeto que seja free ? Alguem tem alguma documentacao de Banco de Dados orientado aObjeto ? ---UOL, o melhor da Internethttp://www.uol.com.br/-- LISTA SOUJAVA http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htmregras da lista: http://www.soujava.org.br/regras.htmhistorico: http://www.mail-archive.com/java-list%40soujava.org.brpara sair da lista: envie email para [EMAIL PROTECTED] - Herval Freire de A. Júnior --- mailto:[EMAIL PROTECTED] http://www.herval.hpg.com.br --- UIN: 2067270 -- - --[The adepts are everywhere... awake! v0.666a]-- -"Erros graves: julgar-se mais do que se é e estimar-se menos do que se merece". -- Goethe
RE: [java-list] Forté
Robson, Veja em : http://wwws.sun.com/software/sundev/jde/buy/index.html Sun[tm] ONE Studio 4 update 1 Community Edition Eliseu Pfaffenseller Analista de Sistemas. -Original Message-From: Robson Dantas Silva [mailto:[EMAIL PROTECTED]Sent: 05 March, 2003 10:13To: [EMAIL PROTECTED]Subject: [java-list] Forté Alguem sabe onde baixo o Forté ? fui no site da Sun, mas pelo que vi, o nome é SUN ONE e é pago?? Robson ---Este email é certificado que não contém vírusChecked by AVG anti-virus system (http://www.grisoft.com).Version: 6.0.459 / Virus Database: 258 - Release Date: 25/2/2003
RE: [java-list] variaveis de ambiente no windows XP
Eduardo, Dica de: http://www.build-more-pages.com/link_directory/dynamic-frameset.html?http://www.onecomputerguy.com/windowsxp_tips.htm = No botão Start(verde) tem um menu de dicas... Adding Environment Variables Added 12/04/02 Since any version of NT does not use an autoexec.bat file, to add environment variables to WindowsXP: 1) Right click on My Computer 2) Select Properties 3) Click on the Advanced tab 4) Click on the Environment Variables button 5) From here you can change it for the system or just the current user. Eliseu Pfaffenseller Analista de Sistemas. -Original Message- From: Eduardo Oliveira [mailto:[EMAIL PROTECTED] Sent: 27 February, 2003 18:05 To: [EMAIL PROTECTED] Subject: [java-list] variaveis de ambiente no windows XP olá a todos, por favor alguem poderia me ajudar, preciso definir as variaveis de ambiente no windows XP não sei como faço, se alguem puder ajudar fico agradecido.. abraço Eduardo ___ Busca Yahoo! O serviço de busca mais completo da Internet. O que você pensar o Yahoo! encontra. http://br.busca.yahoo.com/ -- LISTA SOUJAVA http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] - -- LISTA SOUJAVA http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] -
RE: [java-list] jdk 1.4.0
Gessé, Estou utilizando o SunONE Studio 4 Update 1, Community Edition para desenvolver minhas aplicações +quentes e o JCREATOR para testar fontes, exemplos, etc. Um abraço, Eliseu. PS. O SunONE é uma evolução do Forté. -Original Message- From: Gesse Barros [mailto:[EMAIL PROTECTED]] Sent: 06 February, 2003 18:12 To: [EMAIL PROTECTED] Subject: [java-list] jdk 1.4.0 pessoal , estou estudando o kit do assunto, ja faço algumas coisas de console e outras em AWT. Qual seria a evolução natural ? Jbuilder ? qual a ide mais apropriada para um novato ? grato. Gessé -- LISTA SOUJAVA http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] - -- LISTA SOUJAVA http://www.soujava.org.br - Sociedade de Usuários Java da Sucesu-SP dúvidas mais comuns: http://www.soujava.org.br/faq.htm regras da lista: http://www.soujava.org.br/regras.htm historico: http://www.mail-archive.com/java-list%40soujava.org.br para sair da lista: envie email para [EMAIL PROTECTED] -
RE: [java-list] Configuração JDBC Oracle
Prezado Marcio, Tente isso: 1) Copie os arquivos classes12.zip e classes12.jar(driver baixado da Oracle) para as pastas: - C:\j2sdk1.4.0\jre\lib\ext = pasta lib\ext do seu sdk - C:\Program Files\Java\j2re1.4.0\lib\ext= Idem - C:\forte4j\lib\ext= pasta lib\ext do seu IDE 2) Exemplo de conexão (HOST, DB, USUARIO e SENHA, por sua conta): import java.sql.*; public class ConectaBD{ public static void main (String args[]) { String url = ""> try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection MinhaConexao = DriverManager.getConnection(url,"USUARIO","SENHA"); System.out.println("Conexao realizada com sucesso"); MinhaConexao.close(); } catch(ClassNotFoundException ex) { System.out.println("Driver JDBC não encontrado!"); } catch(SQLException ex) { System.out.println("Problemas na conexao com a fonte de dados"); System.out.println(ex); } }} -Original Message-From: Marcio Guimaraes [mailto:[EMAIL PROTECTED]]Sent: 30 January, 2003 07:20To: [EMAIL PROTECTED]Subject: [java-list] Configuração JDBC Oracle Pessoal, alguem poderia me ajudar pois preciso configurar o JDBC para cessar um banco de dados Oracle ?? Marcio Barbosa [EMAIL PROTECTED]
RE: [java-list] Impressão com o Java
Da uma olhada no site abaixo. Veja o chapter 22 (Printing), do livro Swing... http://www.grandt.com/sbe/ Também ando procurando material sobre Impressão e foi o melhor que achei até agora. Veja também: http://www.mundooo.com.br/php/modules.php?name=Newsfile=articlesid=529 http://www.javaworld.com/javaworld/jw-10-2000/jw-1020-print.html http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20330121.html http://java.sun.com/printing/ http://java.sun.com/products/java-media/2D/forDevelopers/sdk12print.html VER JDCBook: Report.java === import javax.swing.*; import javax.swing.table.*; import java.awt.print.*; import java.util.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.Dimension; public class Report implements Printable{ JFrame frame; JTable tableView; public Report() { frame = new JFrame(Sales Report); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);}}); final String[] headers = {Description, open price, latest price, End Date, Quantity}; final Object[][] data = { {Box of Biros, 1.00, 4.99, new Date(), new Integer(2)}, {Blue Biro, 0.10, 0.14, new Date(), new Integer(1)}, {legal pad, 1.00, 2.49, new Date(), new Integer(1)}, {tape, 1.00, 1.49, new Date(), new Integer(1)}, {stapler, 4.00, 4.49, new Date(), new Integer(1)}, {legal pad, 1.00, 2.29, new Date(), new Integer(5)} }; TableModel dataModel = new AbstractTableModel() { public int getColumnCount() { return headers.length; } public int getRowCount() { return data.length;} public Object getValueAt(int row, int col) { return data[row][col];} public String getColumnName(int column) { return headers[column];} public Class getColumnClass(int col) { return getValueAt(0,col).getClass();} public boolean isCellEditable(int row, int col) { return (col==1);} public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; } }; tableView = new JTable(dataModel); JScrollPane scrollpane = new JScrollPane(tableView); scrollpane.setPreferredSize(new Dimension(500, 80)); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(BorderLayout.CENTER,scrollpane); frame.pack(); JButton printButton= new JButton(); printButton.setText(print me!); frame.getContentPane().add(BorderLayout.SOUTH,printButton); // for faster printing turn double buffering off RepaintManager.currentManager( frame).setDoubleBufferingEnabled(false); printButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent evt) { PrinterJob pj=PrinterJob.getPrinterJob(); pj.setPrintable(Report.this); pj.printDialog(); try{ pj.print(); }catch (Exception PrintException) {} } }); frame.setVisible(true); } public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException { Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.black); int fontHeight=g2.getFontMetrics().getHeight(); int fontDesent=g2.getFontMetrics().getDescent(); //leave room for page number double pageHeight = pageFormat.getImageableHeight()-fontHeight; double pageWidth = pageFormat.getImageableWidth(); double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth(); double scale = 1; if (tableWidth = pageWidth) { scale = pageWidth / tableWidth; } double headerHeightOnPage= tableView.getTableHeader().getHeight()*scale; double tableWidthOnPage=tableWidth*scale; double oneRowHeight=(tableView.getRowHeight()+ tableView.getRowMargin())*scale; int numRowsOnAPage= (int)((pageHeight-headerHeightOnPage)/oneRowHeight); double pageHeightForTable=oneRowHeight*numRowsOnAPage; int totalNumPages= (int)Math.ceil(( (double)tableView.getRowCount())/numRowsOnAPage); if(pageIndex=totalNumPages) { return NO_SUCH_PAGE; } g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); g2.drawString(Page: +(pageIndex+1),(int)pageWidth/2-35, (int)(pageHeight+fontHeight-fontDesent));//bottom center g2.translate(0f,headerHeightOnPage); g2.translate(0f,-pageIndex*pageHeightForTable); //If this piece of the table is smaller than the size available, //clip to the appropriate bounds. if (pageIndex + 1 == totalNumPages) { int lastRowPrinted = numRowsOnAPage * pageIndex;