days
0
3
hours
1
3
minutes
3
2
seconds
1
3
search
They will come in handy

15 useful code snippets for Java developers

Judy Alex
Java

Metal kitchen utensils image via Shutterstock

In this article, Judy Alex, senior creative writer at Ingic.ae, identifies the top 15 useful code snippets for Java developers.

Before talking about Java, let’s crunch some numbers.

Over three billion devices are presently running on Java, five billion Java Cards are being used (Oracle), and over nine million Java developers are working in the IT industry.

With an increasing popularity, Java has become the number 1 choice for developers. It’s robust, scalable, reliable and independent that makes it a must-learn programming language.

Discussed here are some effective Java code snippets for all Java developers out there.

Converting int to String and Strings to int

String a = String.valueOf(2);   //integer to numeric string
int i = Integer.parseInt(a); //numeric string to an int

Converting String to date in Java

java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);

or

SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
Date date = format.parse( myString );

Converting Java util.Date to sql.Date

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Using Java JDBC to connect to 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())
		{
			// do the thing you do
		}
		rs.close();
		ps.close();
	}

	public static void main(String[] args) 
	{
		OracleJdbcTest test = new OracleJdbcTest();
		test.init();
		test.fetch();
	}
}

Using NIO to copy Java file fast

public static void fileCopy( File in, File out )
            throws IOException
    {
        FileChannel inChannel = new FileInputStream( 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)
            int maxCount = (64 * 1024 * 1024) - (32 * 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();
            }
        }
    }

HTTP Proxy setting in Java

System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");

Generating PDF in Java by using iText JAR

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 FileOutputStream(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();
        }
    }
}

Read this article for more details.

Taking screen shots in Java

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));

}
...

Sending the HTTP request and fetching data with Java

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://www.viralpatel.net/blogs/"); BufferedReader br = newBufferedReader(new InputStreamReader(my_url.openStream())); String strTemp =""; while(null != (strTemp = br.readLine())){ System.out.println(strTemp); } }catch (Exception ex) { ex.printStackTrace(); } } }

Creating JSON data in Java

mport org.json.JSONObject; ... ... JSONObject json = new JSONObject(); json.put("city","Mumbai"); json.put("country", "India"); ... String output = json.toString(); ...

Converting Array to Map in Java

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 Japan is " + countryCapitals.get("Japan"));System.out.println("Capital of France is " + countryCapitals.get("France")); } }

Sending HTTP request while fetching data with Java

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://www.viralpatel.net/blogs/"); BufferedReader br = newBufferedReader(new InputStreamReader(my_url.openStream())); String strTemp =""; while(null != (strTemp = br.readLine())){ System.out.println(strTemp); } }catch (Exception ex) { ex.printStackTrace(); } } }

Using Java to send an email

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
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and 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);
}

Get name of current method

String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); 

Appending content to file in Java

Jaxenter out = null;
try {
	out = new Jaxenter (new FileWriter(”filename”, true));
	out.write(”aString”);
} catch (IOException e) {
	// error processing code
} finally {
	if (out != null) {
		out.close();
	}
}

So these are the code snippets that might come in handy. Feel free to contribute if you know more snippets other than those mentioned above.

Author

Judy Alex

Judy Alex is a BS CS and has been working as a senior creative writer in an IT company known as Ingic.ae – a leading provider of Mobile App Design Dubai. A writer by day, a coder by night, Judy has an innate love for learning about new technologies and tactics related to her field.

Twitter: @judyalex3


Comments
comments powered by Disqus