List of Java code snippets for every Java developer should know. Being a Java developer can be quite stressful sometimes. Developers are desperate for any form of help. here is the list of the latest top 10 Java code snippets that will help any Java developer. Luckily, as with any other coding system, Java offers an extensive selection of fixed codes that never change drastically. These snippets can allow developers more freedom to explore and combine their knowledge for better effects.
With that said, let’s look at the most useful code snippets that any Java developer will be happy to have in their arsenal. Java code snippets for Java developers With the need to constantly iterate and come up with new ways to combine Java with other programming languages,
Top 10 Very Useful Java Code Snippets for Java Developers
- Appending text to file
- Connecting to Oracle
- Converting to SQL
- Generating PDF
- Setting up HTTP Proxy
- Screenshots in Java
- Emailing via Java
- Directory Listing
- Image thumbnail
- Compression and ZIP files
1. Appending Text to File
Clients often ask developers to add text to their newly-created code. This text is often used to inform the end-user of certain legal details, technical information or another announcement. However, Java developers spend a lot of time on these codes and are often left with bloated code as a result. Using a simple appendance code that adds text to the file can alleviate much of that frustration:
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();
}
}
2. Connecting to Oracle
Oracle is the de facto hub for Java scripts, developer resources and other goodies that programmers might want access to. Writing the code needed to access Oracle is often prone to accidental mistakes due to its length and complexity. However, the code is stable and fixed in place, meaning that there is no need to write it again every time you want to add it:
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();
}
}
3. Converting to SQL
SQL databases often require specific file formats in order to register correctly. Java scripts are written in util.date need to be converted before they can be used effectively. As it turns out, a simple two-line code can help you convert to SQL fairly easily:
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
4. Generating PDF
PDF generation is something of an oddball when it comes to Java implementation. Developers are required to manually write the code needed to allow for PDF generation of content available on the source site. This can be useful if you are using a writing service to edit and format your content before publishing it again. The code necessary to allow for PDF generation is as follows:
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();
}
}
}
5. Setting up HTTP Proxy
An HTTP proxy can be useful for websites that expect international traffic and want to pass all the checks presented by Google’s SERP. While it’s not difficult to add a proxy to Java code, the process is time-consuming and repetitive since most websites need it. Java developer can use the following code snippet to set up a proxy through HTTP without much effort:
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");
6. Screenshots in Java
Screenshots are a widely sought-after feature in Java-based programs, websites, and applications. When it comes to their implementation, developers are often left scratching their heads with confusion about the coding process. The reason for this is that Java screenshots need to be added in levels, between existing lines of code. Let’s take a look at how the process looks like in practice:
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));
}
7. Emailing via Java
Emails are often sent through their respective dedicated platforms such as Gmail. However, people sometimes like to add email functionality to their company applications and websites and ask developers to do so for them. The process of adding email functionality is fixed and doesn’t require much in terms of customization. This brings us to the code snippet itself:
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);
}
[/code]
8. Directory Listing
Listing directories is something that most administrators and developers like to do. It’s often useful to get the raw data in regard to site content instead of going through everything manually. Luckily, there is a way to streamline both the coding process and the listing itself:
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
9. Image Thumbnail
Application development and web design often require image optimization. Java developers can easily convert high-quality images into usable thumbnails with a few extra lines of code. Fiddling with the custom values will give the developers more or less optimized images depending on their requirements:
private BufferedImage scale(BufferedImage source,double ratio) {
int w = (int) (source.getWidth() * ratio);
int h = (int) (source.getHeight() * ratio);
BufferedImage bi = getCompatibleImage(w, h);
Graphics2D g2d = bi.createGraphics();
double xScale = (double) w / source.getWidth();
double yScale = (double) h / source.getHeight();
AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
g2d.drawRenderedImage(source, at);
g2d.dispose();
return bi;
}
private BufferedImage getCompatibleImage(int w, int h) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
return image;
}
10. Compression and ZIP files
Lastly, one of the more useful code snippets allows Java developers the ability to compress data. ZIP files are often used to transfer and distribute sizeable data through the internet. A few short code strings give Java developers more freedom than a traditional compression program would:
StringBuilder sb = new StringBuilder();
sb.append(“Test String”);
File f = new File(“d:\\test.zip”);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
ZipEntry e = new ZipEntry(“mytext.txt”);
out.putNextEntry€;
byte[] data = sb.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();
out.close();
In Summation
It’s always a good idea to keep a file with all the useful Java code snippets handy. Copying these lines of code is far easier and simpler than writing them from scratch. You will not only save a lot of time and energy in doing so but give yourself the ability to experiment and tinker with existing code. Don’t be afraid to experiment with pre-existing lines of code in order to innovate and pleasantly surprise your clients.
Author’s Bio:
Alaine Gordon is a young and talented content manager. She has been writing professionally since 2010 about almost everything, from psychology to finance. Alaine Gordon graduated from the University of Colorado with B.A. in Journalism, in 2011. She is an open-minded, creative person who loves to make people smile. Her credo is ‘Life is a fun enterprise’. In her free time, she loves travelling, reading science fiction and knitting. Her huge dream is to visit every single country in the world.
0 Comments: