Java
Read an XML document
below is the basic Java DOM approach to reading an xml document (file) into memory
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
Document doc;
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse (new File("FileName"));
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
People say Java is long-winded
Compare the Java code below to the C version underneath
public class HelloWorld {
public static void main(String[] args) {
System.out.println( "I'm Alive!!");
}
}
and in C
#include <stdio.h>
int main() {
printf("Hello World!\n");
return 0;
}
The java version is really only encumbered by one extra statement (the class statement) which, granted my be a little redundant in such a simple case, is not really an issue. The vast majority of beginners just accept that it is part of the language - just a container in which to put code and data.
And here is a much prettier version - it pops up a dialog box and only adds one more line:
import javax.swing.JOptionPane;
public class PopHelloWorld {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "I'm Alive!!", "Hello", JOptionPane.INFORMATION_MESSAGE);
}
}
Round to n significant figures
I needed to round numbers to a given number of significant figures, irrespective of their size, here is an example of what I cam up with:
public static void main(String[] args) {
double vals[] = {123456.00, 1.23456, 0.00123456 };
double sigFigs = 3;
double base10 = Math.log(10);//factor to convert to natural log to base 10
for(double v : vals) {
//get the number of digits in the value
int nDigits = 1 + (int) (Math.round(Math.log(v)/base10));
//create a scaling factor
double factor = Math.pow(10,nDigits) / Math.pow(10,sigFigs);
//divide by the factor, round and multiply to reduce the significant figures
double vSigFigs = Math.round( v/factor) * factor;
/* the double above is pretty close but being a double means that it may not be exact
* convert to a BigDecimal of the correct scale */
BigDecimal bd = new BigDecimal(vSigFigs);
// the scale is the number of digits after the decimal point
int scale = 1 + Math.abs( (int)Math.round( (Math.log(factor)/base10) ) );
bd = bd.setScale( scale , BigDecimal.ROUND_HALF_UP);
System.out.println("Value=" + v + " rounded=" + bd.toPlainString());
}
}
List database tables/columns
Here is a way of listing the tables and columns in a database via JDBC
import java.sql.*;
public class ReadDb {
public static void main(String[] args) {
//open the db
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
// Create a connection to the database
String serverName = "localhost";
String portNumber = "1521";
String sid = "db";
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
String username = "user";
String password = "password";
Connection cnn = DriverManager.getConnection(url, username, password);
String catalog = null;
String schema = null;
for (int i=0; i<args.length; i=i+2) {
{
if (args[i].equals("-cat")) {
catalog = args[i+1];
}
else if (args[i].equals("-scm")) {
schema = args[i+1];
}
}
}
listTables(cnn, catalog, schema);
cnn.close();
}
catch (ClassNotFoundException e) {
// Could not find the database driver
e.printStackTrace();
}
catch (SQLException e) {
// Could not connect to the database
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error in argument list");
}
}
public static void listTables(Connection cnn, String catalog, String schema) {
try {
// Gets the database metadata
DatabaseMetaData dbmd = cnn.getMetaData();
// Specify the type of object; in this case we want tables
String[] types = {"TABLE"};
ResultSet resultSet = dbmd.getTables(null, null, "%", types);
// Get the table names
while (resultSet.next()) {
// Get the table name
String tableName = resultSet.getString(3);
// Get the table's catalog and schema names (if any)
String tableCatalog = resultSet.getString(1);
String tableSchema = resultSet.getString(2);
//should we list this catalog/schema?
boolean listCat = true;
if (catalog != null && !catalog.equals(tableCatalog)) listCat=false;
boolean listScm = true;
if (schema != null && !schema.equals(tableSchema)) listScm=false;
if (listCat && listScm) {
try {
System.out.println('\n' + tableName + "\t" + tableCatalog + "\t" + tableSchema);
//list columns - seems that we need to do a select * from table and
//then get columns from result set
String sql = "SELECT * from " + tableName;
// Create a result set
Statement stmt = cnn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// Get result set meta data
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
// Get the column names; column indices start from 1
for (int i=1; i<numColumns+1; i++) {
try {
String columnName = rsmd.getColumnName(i);
System.out.println( columnName);
} catch (SQLException e) {
System.out.println("Error reading column info for table " + tableName);
e.printStackTrace();
}
}
} catch (SQLException e) {
System.out.println("Error reading column info for table " + tableName);
e.printStackTrace();
}
}//if listCat and listScm
}// while db meta data
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- Login to post comments