Inserting Values From Text File To MySQL

This tutorial shows how you can insert some data from a text file to a MySQL database. You can also extend this to work with other databases by changing the driver.

package com.kushal.utilities;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class InsertTextFromFileToMySql {

public static Connection getConnection() throws Exception {
	String driver = "com.mysql.jdbc.Driver";
	String url = "jdbc:mysql://localhost/sanjaal_com";
	String username = "root";
	String password = "";

	Class.forName(driver);
	Connection conn = DriverManager.getConnection(url,
                                  username, password);
	return conn;
}

public static void main(String[] args) throws Exception {
	String textValue = "";
	int textLength = 0;
	String category = "funny";
	String lineRead = null;
	PreparedStatement pstmt = null;

	String fileNameToInsertTextFrom = "C:/temp/smsCollection002.txt";
	FileReader fileReader = new FileReader(new File(
			fileNameToInsertTextFrom));

	Connection conn = null;
	try {
		conn = getConnection();
		conn.setAutoCommit(false);

		BufferedReader reader = new BufferedReader(fileReader);
		pstmt = conn.prepareStatement(
		"insert into smsTable(sms_text, sms_length, sms_category)"+
		"values (?, ?, ?)");

		while ((lineRead = reader.readLine()) != null) {
			try {
				textValue = lineRead.trim();
				textLength = textValue.length();

				if (textLength > 0) {

					pstmt.setString(1, textValue);
					pstmt.setInt(2, textLength);
					pstmt.setString(3, category);
					pstmt.executeUpdate();
					conn.commit();
				}

			} catch (NullPointerException npe) {
				// do nothing proceed to another line
			}
			lineRead = null;
		}

	} catch (Exception e) {
		System.err.println("Error: " + e.getMessage());
		e.printStackTrace();
	} finally {
		pstmt.close();
		conn.close();
	}
	}
}

Understanding the JUnit Annotations And Their Work

Annotations have made some of the programming stuffs easier because they do a lot of things in the background, which any programmer would otherwise needed to have coded by themselves. JUnit uses a bunch of annotations and represents various separate tasks they do behind the scene. Here are some of the most widely used annotations from Java based Unit Testing Framework – The JUnit. If you would like to see a comprehensive example of JUnit with all these annotations in action, see my previous article on JUnit Test Case

  1. @Test
    • Denotes a test method. Can be used with expected to assert expected results on the object under test.
  2. @Before
    • Run before each test method is run i.e. do a setup
  3. @After
    • Run after each test method is run i.e. do a teardown
  4. @BeforeClass
    • Run before all the tests in a class (Runs once for all of the tests)
  5. @AfterClass
    • Run after all the tests in a class (Runs once for all of the tests)
  6. @Parameters
    • Allows you to run the same test with different data by defining the data parameters. @Parameters have to return List[], and the parameter will pass into class constructor as argument.
  7. @RunWith
    • Exclusively tells the class that the Junit Test Case uses Parameterized runner
  8. @Ignore
    • This allows to skip a test. ¬†You might want to skip a test if you are still working on it or you are not convinced it’s a valid test case or maybe ignore cases which are long running.

Calling URL Browser From Java Application

This program teaches you how you can call the browser in your OS to open the URL that you are passing from your Java application. This program is fully compiled and tested.

package com.kushal.utilities;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 26th August, 2008
 */
import java.lang.reflect.Method;

import javax.swing.JOptionPane;

public class OpenDefaultBrowserFromJava {
	private static final String errMsg = "ERROR WHILE ATTEMPTEING TO LUNCH WEB BROWSER";
	private static final String errFindingBrowser="COULD NOT FIND THE BROWSER";
	
	public static void main(String args [])
	{
		String urlToOpen="http://www.sanjaal.com/java";
		openURL(urlToOpen);
	}

	/**
	 * This method takes URL as a parameter and tries to
	 * identify Operating system and then lunches the broswer
	 * with the given URL
	 */
	public static void openURL(String url) {
		String operatingSystem = System.getProperty("os.name");
		try {
			/*
			 * Check if it is windows OS 
			 */
			if (operatingSystem.startsWith("Windows"))
				Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
			/*
			 * If not windows OS, Check if it is a Mac OS
			 */
			else if (operatingSystem.startsWith("Mac OS")) {
				Class fileManager = Class.forName("com.apple.eio.FileManager");
				Method openURL = fileManager.getDeclaredMethod("openURL",
						new Class[] { String.class });
				openURL.invoke(null, new Object[] { url });
			}
			
			/*
			 * Or, it might be some unix or linux OS
			 */
			else { 
				/**
				 * There are different browsers possible.
				 */
				String[] browsers = { 	"firefox", 
										"netscape",
										"opera", 
										"konqueror", 
										"epiphany", 
										"mozilla"};
				String browser = null;
				
				for (int count = 0; count < browsers.length && browser == null; count++)
					if (Runtime.getRuntime().exec(
							new String[] { "which", browsers[count] })
							.waitFor() == 0)
						browser = browsers[count];

				if (browser == null) 
					throw new Exception(errFindingBrowser);
				else
					Runtime.getRuntime().exec(new String[] { browser, url });
			}

		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, errMsg + ":n" + e.getMessage());
		}
	}

}