Here are 20 very useful pieces of Java program that I hope will be useful to you.
1. Conversion of strings with integral type
String a = string.valueof (2); Integer to numeric string
int. i = Integer.parseint (a);//numeric string to an int
2. Add content to end of file
BufferedWriter out = null;
try {out
= new BufferedWriter (new FileWriter ("filename", true);
Out.write ("astring");
} catch (IOException e) {
//Error processing code
} finally {
if (out!= null) {
out.close ();
}
}
3. Get the name of the current method
String methodname = Thread.CurrentThread (). Getstacktrace () [1].getmethodname ();
4. Turn string to date
Java.util.Date = Java.text.DateFormat.getDateInstance (). Parse (Date String);
Or:
simpledateformat format = new SimpleDateFormat ("DD. Mm.yyyy ");
Date date = Format.parse (myString);
5. Using JDBC to link Oracle
public class Oraclejdbctest {String Driverclass = "Oracle.jdbc.driver.OracleDriver";
Connection con;
public void init (FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {
Properties Props = new properties ();
Props.load (FS);
String url = props.getproperty ("Db.url");
String userName = Props.getproperty ("Db.user");
String Password = props.getproperty ("Db.password");
Class.forName (Driverclass);
Con=drivermanager.getconnection (URL, userName, password); public void Fetch () throws SQLException, IOException {preparedstatement PS = con.preparestatement ("Select
Sysdate from dual ");
ResultSet rs = Ps.executequery ();
while (Rs.next ()) {//Does the thing you do} rs.close ();
Ps.close ();
public static void Main (string[] args) {oraclejdbctest test = new Oraclejdbctest ();
Test.init ();
Test.fetch ();
}
}
6. Util the Java. Date is converted to SQL. Date
Java.util.Date utildate = new Java.util.Date ();
Java.sql.Date sqldate = new Java.sql.Date (Utildate.gettime ());
7. Use of NiO for fast file copies
public static void FileCopy (file in, file out)
throws IOException
{
FileChannel inchannel = new Fileinputstr EAM (in). Getchannel ();
FileChannel Outchannel = new FileOutputStream (out). Getchannel ();
Try
{
// Inchannel.transferto (0, Inchannel.size (), outchannel); Original--apparently has trouble copying large files on Windows
//magic number for Windows, 64MB-32KB)
I NT Maxcount = (1024 * 1024)-(* * 1024);
Long size = Inchannel.size ();
Long position = 0;
while (position < size)
{
position + = Inchannel.transferto (position, Maxcount, Outchannel);
}
finally
{
if (inchannel!= null)
{
inchannel.close ();
}
if (Outchannel!= null)
{
outchannel.close ();
}
}
}
8. Create thumbnails of pictures
private void Createthumbnail (string filename, int thumbwidth, int thumbheight, int quality, string outfilename) thro WS Interruptedexception, FileNotFoundException, IOException {//load image from filename image image = Toolk
It.getdefaulttoolkit (). getImage (filename);
Mediatracker mediatracker = new Mediatracker (new Container ());
Mediatracker.addimage (image, 0);
Mediatracker.waitforid (0);
Use the ' to ' test for errors in this point:System.out.println (Mediatracker.iserrorany ());
Determine thumbnail size from WIDTH and HEIGHT double thumbratio = (double) thumbwidth/double thumbheight;
int imagewidth = Image.getwidth (null);
int imageheight = Image.getheight (null);
Double imageratio = (double) imagewidth/(double) imageheight;
if (Thumbratio < imageratio) {thumbheight = (int) (thumbwidth/imageratio);
else {thumbwidth = (int) (thumbheight * imageratio); }//Draw original imageTo thumbnail image object and//scale it to the new size on-the-fly bufferedimage thumbimage = new Bufferedimag
E (Thumbwidth, Thumbheight, Bufferedimage.type_int_rgb);
Graphics2D graphics2d = Thumbimage.creategraphics ();
Graphics2d.setrenderinghint (Renderinghints.key_interpolation, renderinghints.value_interpolation_bilinear);
Graphics2d.drawimage (image, 0, 0, thumbwidth, thumbheight, NULL); Save thumbnail image to outfilename bufferedoutputstream out = new Bufferedoutputstream (New FileOutputStream (Outfi
Lename));
JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (out);
JPEGEncodeParam param = 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 ();
}
9. Create JSON-formatted data
And the following jar file: Json-rpc-1.0.jar (KB)
Import Org.json.JSONObject;
...
...
Jsonobject json = new Jsonobject ();
Json.put ("City", "Mumbai");
Json.put ("Country", "India");
...
String output = json.tostring ();
...
10. Using Itext jar to generate PDF
import java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.OutputStream;
Import Java.util.Date;
Import com.lowagie.text.Document;
Import Com.lowagie.text.Paragraph;
Import Com.lowagie.text.pdf.PdfWriter; public class Generatepdf {public static void main (string[] args) {try {outputstream file = new Fileout
Putstream (New File ("C:\\test.pdf"));
Document document = new document ();
Pdfwriter.getinstance (document, file);
Document.open ();
Document.add (New Paragraph ("Hello Kiran"));
Document.add (New Paragraph () (New Date (). toString ()));
Document.close ();
File.close ();
catch (Exception e) {e.printstacktrace (); }
}
}
One. HTTP Proxy settings
system.getproperties (). Put ("Http.proxyhost", "Someproxyurl");
System.getproperties (). Put ("Http.proxyport", "Someproxyport");
System.getproperties (). Put ("Http.proxyuser", "someusername");
System.getproperties (). Put ("Http.proxypassword", "Somepassword");
12. Single Instance Singleton sample
public class Simplesingleton {
private static Simplesingleton singleinstance = new Simplesingleton ();
Marking default constructor Private
//to Avoid direct instantiation.
Private Simplesingleton () {
}
//get instance for class Simplesingleton public
static Simplesingleton GetInstance () {return
singleinstance;
}
}
Another kind of implementation
public enum Simplesingleton {
INSTANCE;
public void DoSomething () {
}
}
//call the "method" from Singleton:
SimpleSingleton.INSTANCE.doSomething ();
13. Screen-catching procedure
Import java.awt.Dimension;
Import Java.awt.Rectangle;
Import Java.awt.Robot;
Import Java.awt.Toolkit;
Import Java.awt.image.BufferedImage;
Import Javax.imageio.ImageIO;
Import Java.io.File;
...
public void Capturescreen (String fileName) throws Exception {
Dimension screensize = Toolkit.getdefaulttoolkit (). Getscreensize ();
Rectangle screenrectangle = new Rectangle (screensize);
Robot Robot = new Robot ();
BufferedImage image = Robot.createscreencapture (screenrectangle);
Imageio.write (Image, "PNG", New File (FileName));
}
...
14. listing files and directories
file dir = new File ("DirectoryName");
String[] Children = dir.list (); if (children = = null) {//either Dir does not exist or are not. A directory} else {for (int i=0; i < Childre N.length;
i++) {//Get filename of file or directory String filename = children[i];
}//It is also possible to filter the list of returned files.
This example does "not return" any of the files that are start with '. ' FilenameFilter filter = new FilenameFilter () {public Boolean accept (File dir, String name) {return!name.start
Swith (".");
}
};
Children = dir.list (filter);
The list of files can also be retrieved as File objects file[] files = dir.listfiles (); This filter is returns directories FileFilter FileFilter = new FileFilter () {public boolean accept (file file)
{return file.isdirectory ();
}
};
Files = dir.listfiles (filefilter);
15. Create Zip and jar files
Import java.util.zip.*;
Import java.io.*;
public class Zipit {public static void main (String args[]) throws IOException {if (Args.length < 2) {
System.err.println ("Usage:java zipit zip.zip file1 file2");
System.exit (-1);
} File ZipFile = new file (Args[0]);
if (zipfile.exists ()) {System.err.println ("Zip file already exists, please try another");
System.exit (-2);
FileOutputStream fos = new FileOutputStream (ZipFile);
Zipoutputstream Zos = new Zipoutputstream (FOS);
int bytesread;
byte[] buffer = new byte[1024];
CRC32 CRC = New CRC32 ();
for (int i=1, n=args.length i < n; i++) {String name = Args[i];
File File = new file (name);
if (!file.exists ()) {System.err.println ("skipping:" + name);
Continue
Bufferedinputstream bis = new Bufferedinputstream (new FileInputStream (file));
Crc.reset (); while (BytesreaD = bis.read (buffer))!=-1) {crc.update (buffer, 0, bytesread);
} bis.close ();
Reset to beginning of input stream bis = new Bufferedinputstream (new FileInputStream (file));
ZipEntry entry = new ZipEntry (name);
Entry.setmethod (zipentry.stored);
Entry.setcompressedsize (File.length ());
Entry.setsize (File.length ());
ENTRY.SETCRC (Crc.getvalue ());
Zos.putnextentry (entry);
while ((bytesread = bis.read (buffer))!=-1) {zos.write (buffer, 0, bytesread);
} bis.close ();
} zos.close ();
}
}
16. Parse/Read XML file
XML file
<?xml version= "1.0"?>
<students>
<student>
<name>John</name>
< grade>b</grade>
<age>12</age>
</student>
<student>
<name >Mary</name>
<grade>A</grade>
<age>11</age>
</student>
<student>
<name>Simon</name>
<grade>A</grade>
<age>18 </age>
</student>
</students>
Java code
Package net.viralpatel.java.xmlparser;
Import Java.io.File;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList; public class Xmlparser {public void Getallusernames (String fileName) {try {documentbuilderfactory dbf
= Documentbuilderfactory.newinstance ();
Documentbuilder db = Dbf.newdocumentbuilder ();
File File = new file (fileName);
if (file.exists ()) {Document doc = db.parse (file);
Element Docele = Doc.getdocumentelement (); Print root element of the document SYSTEM.OUT.PRINTLN ("root element of the document:" + docele.ge
Tnodename ());
NodeList studentlist = docele.getelementsbytagname ("student"); Print total student elements into document System.out. println ("Total Students:" + StudentliSt.getlength ()); if (studentlist!= null && studentlist.getlength () > 0) {for (int i = 0; i < Studentlist.getleng Th ();
i++) {Node node = Studentlist.item (i); if (node.getnodetype () = = Node.element_node) {System.out. println ("==================
===");
Element e = (element) node;
NodeList nodelist = e.getelementsbytagname ("name"); System.out.println ("Name:" + nodelist.item (0). Getchildnodes (). Item (0). Getnodeva
Lue ());
NodeList = E.getelementsbytagname ("Grade"); System.out.println ("Grade:" + nodelist.item (0). Getchildnodes (). Item (0). Getnodev
Alue ());
NodeList = E.getelementsbytagname ("Age");
System.out.println ("Age:" + nodelist.item (0). Getchildnodes (). Item (0) . Getnodevalue ());
}} else {system.exit (1);
catch (Exception e) {System.out.println (e);
} public static void Main (string[] args) {xmlparser parser = new Xmlparser ();
Parser.getallusernames ("C:\\test.xml"); }
}
17. Convert Array to Map
Import Java.util.Map;
Import 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 "}};
map countrycapitals = arrayutils.tomap (countries);
System.out.println ("Capital of the Japan is" + countrycapitals.get ("Japan"));
System.out.println ("Capital of France are" + countrycapitals.get ("France"));
}
18. Send Mail
Import javax.mail.*;
Import javax.mail.internet.*;
Import java.util.*;
public void Postmail (string recipients[], string subject, String message, string from) throws Messagingexception {
Boolean debug = false;
Set the host SMTP Address Properties props = new properties ();
Props.put ("Mail.smtp.host", "smtp.example.com");
Create some properties and get the default session sessions = Session.getdefaultinstance (props, null);
Session.setdebug (Debug);
Create a message msg = new MimeMessage (session);
Set the "from" to "address" internetaddress Addressfrom = new internetaddress (from);
Msg.setfrom (Addressfrom);
internetaddress[] Addressto = new Internetaddress[recipients.length];
for (int i = 0; i < recipients.length i++) {Addressto[i] = new InternetAddress (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);
}
19. HTTP request to send generation data
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import Java.net.URL;
public class Main {public
static void Main (string[] args) {
try {
url my_url = new URL ("http://coolshell.cn/" );
BufferedReader br = new BufferedReader (New InputStreamReader (My_url.openstream ()));
String strtemp = "";
while (null!= (strtemp = Br.readline ())) {
System.out.println (strtemp);
}
catch (Exception ex) {
Ex.printstacktrace ();}}
20. Change the size of the array
/** * 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. * * Private static object Resizearray (object oldarray, int newsize) {int oldsize = Java.lang.reflect.Array.getLength (o
Ldarray);
Class ElementType = Oldarray.getclass (). Getcomponenttype ();
Object NewArray = java.lang.reflect.Array.newInstance (elementtype,newsize);
int preservelength = Math.min (oldsize,newsize);
if (Preservelength > 0) system.arraycopy (oldarray,0,newarray,0,preservelength);
return newarray;
//Test routine for Resizearray ().
public static void Main (string[] args) {int[] a = {1,2,3};
A = (int[]) Resizearray (a,5);
A[3] = 4;
A[4] = 5;
for (int i=0; i<a.length; i++) System.out.println (a[i)); }
Hopefully this article will help you learn about Java programming.