Abaixo estão 20 trechos de programa Java muito úteis, espero que seja útil para você.
1. As cordas têm conversão inteira
String a = string.valueof (2); // Inteiro para String numérico int i = Integer.parseInt (a); // string numérica para um int
2. Adicione conteúdo ao final do arquivo
Bufferwriter out = null; tente {out = new BufferWriter (new FileWriter ("nome do arquivo", true)); out.write ("Astring"); } catch (ioexception e) {// Código de processamento de erro} finalmente {if (out! = null) {out.close (); }} 3. Obtenha o nome do método atual
String MethodName = Thread.currentThread (). GetStackTrace () [1] .getMethodName ();
4. Vire a corda até o momento
java.util.date = java.text.dateFormat.getDateInstance (). parse (date string); ou: simpledateFormat format = new SimpleDateFormat ("dd.mm.yyyy"); Data data = format.parse (mystring); 5. Link Oracle com JDBC
classe pública oraclejdbctest {string driverclass = "oracle.jdbc.driver.oracledriver"; Conexão con; public void init (FileInputStream FS) lança ClassNotFoundException, SQLEXCECCETION, FILENOTFOUNDEXCECCECTION, IOException {Properties Props = new Properties (); props.load (fs); String url = props.getproperty ("db.url"); String userName = props.getProperty ("db.user"); String senha = props.getProperty ("db.password"); Class.ForName (DriverClass); con = driverManager.getConnection (URL, nome de usuário, senha); } public void fetch () lança sqLexception, ioexception {preparadostatement ps = con.preparestatement ("selecione sysdate de dual"); ResultSet rs = ps.executeQuery (); while (rs.Next ()) {// Faça o que você faz} rs.close (); ps.close (); } public static void main (string [] args) {oraclejdbctest test = new oraclejdbctest (); test.init (); test.fetch (); }} 6. Converta Java Util.date em sql.date
java.util.date ustildate = new java.util.date (); java.sql.date sqldate = new java.sql.date (ustildate.gettime ());
7. Use Nio para copiar de arquivos rápidos
public static void filecopy (arquivo in, file out) lança ioexception {filechannel Inchannel = new FileInputStream (in) .getChannel (); FileChannel Outchannel = new FileOutputStream (out) .getChannel (); tente {// Inchannel.Transferto (0, Inchannel.size (), outchannel); // Original - aparentemente tem problemas para copiar arquivos grandes no Windows // Magic Number for Windows, 64MB - 32kb) int maxCount = (64 * 1024 * 1024) - (32 * 1024); tamanho longo = INCHANNEL.SIZE (); posição longa = 0; while (posição <size) {position += Inchannel.Transferto (posição, maxcount, outchannel); }} finalmente {if (Inchannel! = null) {Inchannel.close (); } if (outchannel! = null) {outchannel.close (); }}} 8. Crie miniaturas de imagens
Void privado CreateThumbNail (nome do arquivo da string, Int Whumbwidth, Int ThumbHeight, Int Quality, String OutfileName) lança interruptedException, filenotfoundException, ioException {// carregar imagem da imagem da imagem da imagem = Toolkit.getDefaultToolkit (). getImage (arquivoname); MediaTracker MediaTracker = New MediaTracker (new Container ()); MediaTracker.addimage (imagem, 0); MediaTracker.waitforid (0); // Use isso para testar erros neste momento: System.out.println (MediaTracker.ISERRORANY ()); // determinar o tamanho da miniatura da largura e da altura dupla de thumbratio = (dupla) largura de miniatura / (dupla) ThumbHeight; int imagewidth = image.getwidth (null); int imageHeight = image.getHeight (nulo); Double Imageratio = (Double) ImageWidth / (Double) ImageHeight; if (thumbratio <imageratio) {thumbheight = (int) (largura de thumbidth / imageratio); } else {thumbwidth = (int) (thumbheight * imageratio); } // Desenhe a imagem original para o objeto de imagem em miniatura e // escala-o para o novo tamanho on-the-flly bufferimage thumbimage = new bufferiMage (largura de thumbid, thumbhesed, bufferImage.type_int_rgb); Graphics2D Graphics2D = Thumbimage.CreateGraphics (); Graphics2d.setRanderingHint (renderinghints.key_interpolation, renderinghints.value_interpolation_bilinear); Graphics2d.Drawimage (imagem, 0, 0, largura de Thumb, thumbheight, nulo); // Salvar a imagem de miniatura para superar o nome do bufferoudOutputStream out = new BufferoudOutputStream (new FileOutputStream (outfileName)); JpegImageEncoder coder = jpegCodec.createjpegencoder (out); JPEGENCODEPARAM param = coder.getDefaultJpegencodeParam (Thumbimage); qualidade = math.max (0, math.min (qualidade, 100)); param.setQuality ((float) Quality / 100.0f, false); coder.setJpegencodeParam (param); coder.encode (thumbimage); out.Close (); }9. Crie dados de formato JSON
E o seguinte arquivo JAR: JSON-RPC-1.0.JAR (75 KB)
importar org.json.jsonObject; ... ... JsonObject json = new JsonObject (); json.put ("City", "Mumbai"); json.put ("country", "Índia"); ... string output = json.toString (); ... 10. Gere pdf usando o jart iText
importar java.io.file; importar java.io.fileOutputStream; importar java.io.OutputStream; importar java.util.date; importação com.lowagie.text.document; importação com.lowagie.text.paragraph; importação com.lowagie.text.pdf.pdfwriter; classe pública generatepdf {public static void main (string [] args) {try {outputStream File = new FileOutputStream (novo arquivo ("c: //test.pdf")); Documento documento = new document (); Pdfwriter.getInstance (documento, arquivo); document.open (); document.add (novo parágrafo ("Hello Kiran")); document.add (novo parágrafo (new Date (). ToString ())); document.close (); file.close (); } catch (Exceção e) {e.printStackTrace (); }}} 11. Configurações de proxy HTTP
System.getProperties (). Put ("http.proxyhost", "algumproxyurl");
System.getProperties (). Put ("http.proxyport", "algumproxyport");
System.getProperties (). Put ("http.proxyuser", "algum nome");
System.getProperties (). Put ("http.proxyPassword", "Somepassword");
12. Exemplo de única instância
classe pública Simplesingleton {private static simpleleton singleInstance = new SimpleLePingleton (); // Marcar o construtor padrão privado // para evitar a instanciação direta. private simpleingleton () {} // obtenha instância para classe simpleingleton public static simpleleton getInstance () {return singenInstance; }} Outra implementação
public enum simpleingleton {instance; public void Dosomething () {}} // Ligue para o método de Singleton: Simpleingleton.instance.Dosomething (); 13. Programa de captura de tela
importar java.awt.dimension; importar java.awt.rectangle; importar java.awt.robot; importar java.awt.toolkit; importar java.awt.image.bufferiMage; importar javax.imageio.imageio; importar java.io.file; ... public void Capturescreen (nome do arquivo de string) lança exceção {dimension screenSize = Toolkit.getDefaultToolkit (). getScreensize (); Retângulo ScreenRectangle = novo retângulo (Screensize); Robô robot = new robot (); BufferImage imagem = robot.createsCreencapture (screenRectangle); Imageio.write (imagem, "png", novo arquivo (nome do arquivo)); } ... 14. Liste arquivos e diretórios
Arquivo dir = novo arquivo ("DirectoryName"); String [] crianças = Dir.List (); if (crianças == null) {// qualquer Dir não existe ou não é um diretório} else {for (int i = 0; i <children.length; i ++) {// obtenha o nome do arquivo de arquivo ou string de diretório nome = filhos [i]; }} // também é possível filtrar a lista de arquivos retornados. // Este exemplo não retorna arquivos que começam com `. '. Filenamefilter filtro = new filenamefilter () {public boolean aceit (name de string de arquivo, nome da string) {return! Name.startswith ("."); }}; crianças = dir.list (filtro); // A lista de arquivos também pode ser recuperada como arquivos de objetos de arquivo [] arquivos = dir.listfiles (); // Este filtro retorna apenas os diretórios FileFilter FileFilter = new FileFilter () {public boolean Acep (arquivo file) {return file.isdirectory (); }}; arquivos = dir.listfiles (FileFilter); 15. Crie arquivos zip e jar
importar java.util.zip.*; importar java.io.*; classe pública zipit {public static void main (string args []) lança ioexception {if (args.length <2) {System.err.println ("Uso: java zipit zip.zip file1 file1 file2"); System.Exit (-1); } Arquivo zipfile = novo arquivo (args [0]); if (zipfile.exists ()) {System.err.println ("O arquivo zip já existe, tente outro"); System.Exit (-2); } FileOutputStream fos = new FileOutputStream (zipFile); ZipOutputStream zos = new ZipOutputStream (fos); int bytesread; byte [] buffer = novo byte [1024]; CRC32 CRC = novo CRC32 (); for (int i = 1, n = args.length; i <n; i ++) {string name = args [i]; Arquivo de arquivo = novo arquivo (nome); if (! file.exists ()) {System.err.println ("Skipping:" + Name); continuar; } BufferInputStream bis = new bufferInputStream (new FileInputStream (File)); CRC.Reset (); while ((bytesread = bis.read (buffer))! = -1) {crc.update (buffer, 0, bytesread); } bis.close (); // Redefinir para o início do fluxo de entrada bis = new bufferInputStream (new FileInputStream (arquivo)); Entrada de zipentry = new Zipentry (nome); entrada.setMethod (zipentry.stored); entrada.SetCompressEdSize (file.Length ()); entrada.SetSize (file.Length ()); entrada.setcrc (crc.getValue ()); zos.putNextEntry (entrada); while ((bytesread = bis.read (buffer))! = -1) {zos.write (buffer, 0, bytesread); } bis.close (); } zos.close (); }}16. Analisando/lendo Arquivos XML
Arquivos XML
<? xml versão = "1.0"?> <dudits> <estudante> <name> john </name> <rade> b </ruda> <eane> 12 </a Age> </student> <denty> <name> Mary </name> </grau </grau> <routh> <eane> 11 </idade
Código Java
pacote net.viralpatel.java.xmlparser; importar java.io.file; importar javax.xml.parsers.documentBuilder; importar javax.xml.parsers.documentBuilderFactory; importar org.w3c.dom.document; importar org.w3c.dom.Element; importar org.w3c.dom.node; importar org.w3c.dom.nodelist; public class XmlParser {public void getAllerNames (string fileName) {try {documentBuilderFactory dbf = documentBuilderFactory.NewInstance (); Documentbuilder db = dbf.newdocumentBuilder (); Arquivo de arquivo = novo arquivo (nome do arquivo); if (file.exists ()) {document doc = db.parse (arquivo); Elemento docele = doc.getDocumentElement (); // Imprime o elemento raiz do documento System.out.println ("Elemento raiz do documento:" + docele.getNodename ()); Nodelist StudentList = Docele.GetElementsByTagName ("Student"); // Imprima o total de elementos do aluno no documento System.out .println ("Total de alunos:" + StudentList.getLength ()); if (StudentList! = null && StudentList.getLength ()> 0) {for (int i = 0; i <studentList.getLength (); i ++) {node = studentList.item (i); if (node.getNodEType () == Node.Element_Node) {System.out .println ("====================="); Nó do elemento e = (elemento); Nodelist nodelist = e.getElementsByTagName ("nome"); System.out.println ("Nome:" + nodelist.item (0) .getChildNodes (). Item (0) .getNodEvalue ()); nodelist = e.getElementsByTagName ("grau"); System.out.println ("Grade:" + NodElist.item (0) .getChildNodes (). Item (0) .getNodEvalue ()); nodelist = e.getElementsByTagName ("idade"); System.out.println ("Age:" + nodelist.item (0) .getChildNodes (). Item (0) .getNodEvalue ()); }} else {System.exit (1); }}} catch (Exceção e) {System.out.println (e); }} public static void main (string [] args) {xmlparser parser = new xmlParser (); parser.getAllUserNames ("c: //test.xml"); }} 17. Converta a matriz para mapear
importar java.util.map; importar org.apache.commons.lang.arrayutils; public class Main { public static void main(String[] args) { String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" }, { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } }; Mapa countrycapitals = Arrayutils.TOMAP (países); System.out.println ("Capital do Japão é" + countrycapitals.get ("Japão")); System.out.println ("Capital da França é" + countrycapitals.get ("França")); }} 18. Envie e -mail
importar javax.mail.*; importar javax.mail.internet.*; importar java.util.*; public void Postmail (destinatários da String [], String Assunto, String Mensagem, String de) lança MessagingException {boolean debug = false; // Defina as propriedades do endereço SMTP do host Props = new Properties (); props.put ("Mail.smtp.host", "smtp.example.com"); // Crie algumas propriedades e obtenha a sessão de sessão padrão = session.getDefaultInstance (adereços, nulo); session.setDebug (Debug); // Crie uma mensagem de mensagem msg = new Mimemessage (sessão); // Defina o de e abordam o internetDrEDREDFROM = new InternetAddress (de); msg.setFrom (endereçoFrom); InternetAddress [] endereço para = new InternetAddress [receptories.Length]; for (int i = 0; i <receptories.length; i ++) {endereço para [i] = new InternetDdress (destinatários [i]); } msg.setRecipients (message.recipientType.to, endereço para); // Opcional: você também pode definir seus cabeçalhos personalizados no email se desejar msg.addheader ("myheadername", "myheadValue"); // Definindo o assunto e o conteúdo do tipo msg.SetSubject (sujeito); msg.setContent (Mensagem, "Text/Plain"); Transport.send (msg); } 19. Envie solicitações HTTP para geração de dados
importar java.io.bufferedReader; importar java.io.inputStreamReader; importar java.net.url; classe pública main {public static void main (string [] args) {try {url my_url = new url ("http://coolshell.cn/"); BUBLEREDRADER BR = new BufferredReader (novo InputStreamReader (my_url.openstream ())); String strtemp = ""; while (null! = (strTemp = Br.readline ())) {System.out.println (strTemp); }} catch (Exceção ex) {ex.PrintStackTrace (); }}} 20. Altere o tamanho da matriz
/** * Realina uma matriz com um novo tamanho e copia o conteúdo * da matriz antiga para a nova matriz. * @param OldArray The Old Array, para ser realocado. * @param notificar o novo tamanho da matriz. * @return Uma nova matriz com o mesmo conteúdo. */RESIZEARRAÇÃO DE ESTÁTICO PRIVADO (Object OldArray, Int Newsize) {int OldSize = java.lang.reflect.array.getLength (OldArray); Classe elementType = OldArray.getClass (). GetComponentType (); Objeto newArray = java.lang.reflect.array.newinstance (elementType, Newsize); int preservelngth = math.min (OldSize, Newsize); if (preserveLen comprimento> 0) System.arrayCopy (OldArray, 0, NewArray, 0, Preservel Comngth); retornar newarray; } // Rotina de teste para Resazearray (). public static void main (string [] args) {int [] a = {1,2,3}; a = (int []) resazearray (a, 5); a [3] = 4; a [4] = 5; for (int i = 0; i <A.Length; i ++) System.out.println (a [i]); }Espero que este artigo seja útil para que todos aprendam a programação Java.