publicclassOracleJDBCTest{StringdriverClass="oracle.jdbc.driver.OracleDriver";Connectioncon;publicvoidinit(FileInputStreamfs)throwsClassNotFoundException,SQLException,FileNotFoundException,IOException{Propertiesprops=newProperties();props.load(fs);Stringurl=props.getProperty("db.url");Stringusername=props.getProperty("db.username");Stringpassword=props.getProperty("db.password");Class.forName(driverClass);con=DriverManager.getConnection(url,username,password);}publicvoidfetch()throwsSQLException,IOException{PreparedStatementps=con.prePareStatement("select SYSDATE from dual");ResultSetrs=ps.executeQuery();while(rs.next()){// do the things you do}rs.close();ps.close();}publicstaticvoidmain(String[]args){OracleJDBCTesttest=newOracleJDBCTest();test.init();test.fetch();}}
publicstaticvoidfileCopy(Filein,Fileout)throwsIOException{FileChannelinChannel=newFileInputStream(in).getChannel();FileChanneloutChannel=newFileOutputStream(in).getChannel();try{// inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows// magic number for Windows, 64Mb - 32Kb)intmaxCount=(64*1024*1024)-(32*1024);longsize=inChannel.size();longposition=0;while(position<size){position+=inChannel.transferTo(position,maxCount,outChannel);}}finally{if(inChannel!=null){inChannel.close();}if(outChannel!=null){outChannel.close();}}}
privatevoidcreateThumbnail(Stringfilename,intthumbWidth,intthumbHeight,intquality,StringoutFilename)throwsInterruptedException,FileNotFoundException,IOException{// load image from filename Imageimage=Toolkit.getDefaultToolkit().getImage(filename);MediaTrackermediaTracker=newMediaTracker(newContainer());mediaTracker.addImage(image,0);mediaTracker.waitForID(0);// test for errors at this point: System.out.println(mediaTracker.isErrorAny()); // determine thumbnail size from WIDTH and HEIGHT doublethumbRatio=(double)thumbWidth/(double)thumbHeight;intimageWidth=image.getWidth(null);intimageHeight=image.getHeight(null);doubleimageRatio=(double)imageWidth/(double)imageHeight;if(thumbRatio<imageRatio){thumbHeight=(int)(thumbWidth/imageRatio);}else{thumbWidth=(int)(thumbHeight*imageRatio);}// draw original image to thumbnail image object and // scale it to the new size on-the-fly BufferedImagethumbImage=newBufferedImage(thumbWidth,thumbHeight,BufferedImage.TYPE_INT_RGB);Graphics2Dgraphics2D=thumbImage.createGraphics();graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);graphics2D.drawImage(image,0,0,thumbWidth,thumbHeight,null);// save thumbnail image to outFilename BufferedOutputStreamout=newBufferedOutputStream(newFileOutputStream(outFilename));JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out);JPEGEncodeParamparam=encoder.getDefaultJPEGEncodeParam(thumbImage);quality=Math.max(0,Math.min(quality,100));param.setQuality((float)quality/100.0f,false);encoder.setJPEGEncodeParam(param);encoder.encode(thumbImage);out.close();}
publicclassSimpleSingleton{privatestaticSimpleSingletonsingleInstance=newSimpleSingleton();//Marking default constructor private //to avoid direct instantiation. privateSimpleSingleton(){}//Get instance for class SimpleSingleton publicstaticSimpleSingletongetInstance(){returnsingleInstance;}}
Filedir=newFile("directoryName");String[]children=dir.list();if(children==null){// Either dir does not exist or is not a directory }else{for(inti=0;i<children.length;i++){// Get filename of file or directory Stringfilename=children[i];}}// It is also possible to filter the list of returned files. // This example does not return any files that start with '.'. FilenameFilterfilter=newFilenameFilter(){publicbooleanaccept(Filedir,Stringname){return!name.startsWith(".");}};children=dir.list(filter);// The list of files can also be retrieved as File objects File[]files=dir.listFiles();// This filter only returns directories FileFilterfileFilter=newFileFilter(){publicbooleanaccept(Filefile){returnfile.isDirectory();}};files=dir
packagenet.viralpatel.java.xmlparser;importjava.io.File;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;publicclassXMLParser{publicvoidgetAllUserNames(StringfileName){try{DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();DocumentBuilderdb=dbf.newDocumentBuilder();Filefile=newFile(fileName);if(file.exists()){Documentdoc=db.parse(file);ElementdocEle=doc.getDocumentElement();// Print root element of the document System.out.println("Root element of the document: "+docEle.getNodeName());NodeListstudentList=docEle.getElementsByTagName("student");// Print total student elements in document System.out.println("Total students: "+studentList.getLength());if(studentList!=null&&studentList.getLength()>0){for(inti=0;i<studentList.getLength();i++){Nodenode=studentList.item(i);if(node.getNodeType()==Node.ELEMENT_NODE){System.out.println("=====================");Elemente=(Element)node;NodeListnodeList=e.getElementsByTagName("name");System.out.println("Name: "+nodeList.item(0).getChildNodes().item(0).getNodeValue());nodeList=e.getElementsByTagName("grade");System.out.println("Grade: "+nodeList.item(0).getChildNodes().item(0).getNodeValue());nodeList=e.getElementsByTagName("age");System.out.println("Age: "+nodeList.item(0).getChildNodes().item(0).getNodeValue());}}}else{System.exit(1);}}}catch(Exceptione){System.out.println(e);}}publicstaticvoidmain(String[]args){XMLParserparser=newXMLParser();parser.getAllUserNames("c:\\test.xml");}}
importjava.util.Map;importorg.apache.commons.lang.ArrayUtils;publicclassMain{publicstaticvoidmain(String[]args){String[][]countries={{"United States","New York"},{"United Kingdom","London"},{"Netherland","Amsterdam"},{"Japan","Tokyo"},{"France","Paris"}};MapcountryCapitals=ArrayUtils.toMap(countries);System.out.println("Capital of Japan is "+countryCapitals.get("Japan"));System.out.println("Capital of France is "+countryCapitals.get("France"));}}
importjavax.mail.*;importjavax.mail.internet.*;importjava.util.*;publicvoidpostMail(Stringrecipients[],Stringsubject,Stringmessage,Stringfrom)throwsMessagingException{booleandebug=false;//Set the host smtp address Propertiesprops=newProperties();props.put("mail.smtp.host","smtp.example.com");// create some properties and get the default Session Sessionsession=Session.getDefaultInstance(props,null);session.setDebug(debug);// create a message Messagemsg=newMimeMessage(session);// set the from and to address InternetAddressaddressFrom=newInternetAddress(from);msg.setFrom(addressFrom);InternetAddress[]addressTo=newInternetAddress[recipients.length];for(inti=0;i<recipients.length;i++){addressTo[i]=newInternetAddress(recipients[i]);}msg.setRecipients(Message.RecipientType.TO,addressTo);// Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName","myHeaderValue");// Setting the Subject and Content Type msg.setSubject(subject);msg.setContent(message,"text/plain");Transport.send(msg);}
/** * Reallocates an array with a new size, and copies the contents * of the old array to the new array. * @param oldArray the old array, to be reallocated. * @param newSize the new array size. * @return A new array with the same contents. */privatestaticObjectresizeArray(ObjectoldArray,intnewSize){intoldSize=java.lang.reflect.Array.getLength(oldArray);ClasselementType=oldArray.getClass().getComponentType();ObjectnewArray=java.lang.reflect.Array.newInstance(elementType,newSize);intpreserveLength=Math.min(oldSize,newSize);if(preserveLength>0)System.arraycopy(oldArray,0,newArray,0,preserveLength);returnnewArray;}// Test routine for resizeArray(). publicstaticvoidmain(String[]args){int[]a={1,2,3};a=(int[])resizeArray(a,5);a[3]=4;a[4]=5;for(inti=0;i<a.length;i++)System.out.println(a[i]);}