The following example shows how to use OpenBabel from Java. It includes an example of file format conversion, iteration over atoms, and using the SMARTS matcher.
import org.openbabel.*;The output is as follows:
public class Test {
public static void main(String[] args) {
// Initialise
System.loadLibrary("openbabel_java");
// Read molecule from SMILES string
OBConversion conv = new OBConversion();
OBMol mol = new OBMol();
conv.SetInFormat("smi");
conv.ReadString(mol, "C(Cl)(=O)CCC(=O)Cl");
// Print out some general information on the molecule, atoms
conv.SetOutFormat("can");
System.out.print("Canonical SMILES: " + conv.WriteString(mol));
System.out.println("The molecular weight of the molecule is "
+ mol.GetMolWt());
for(OBAtom atom : new OBMolAtomIter(mol)) {
System.out.println("Atom " + atom.GetIdx() +
": atomic number = " + atom.GetAtomicNum() +
", hybridisation = " + atom.GetHyb());
}
// What are the indices of the carbon atoms
// of the acid chloride groups?
OBSmartsPattern acidpattern = new OBSmartsPattern();
acidpattern.Init("C(=O)Cl");
acidpattern.Match(mol);
vvInt matches = acidpattern.GetUMapList();
System.out.println("There are " + matches.size() +
" acid chloride groups");
System.out.print("The carbon atoms of the matches are: ");
for(int i=0; i<matches.size(); i++)
System.out.print(matches.get(i).get(0) + " ");
}
}
Canonical SMILES: ClC(=O)CCC(=O)ClNote: although using OpenBabel from Eclipse on Windows works fine, some users have reported problems on Linux with the default OpenBabel build. You probably need to build OpenBabel statically on Linux if you want to use it from Eclipse, but I haven't tested this. In any case, you can just compile it from the command line.
The molecular weight of the molecule is 154.97935999999999
Atom 1: atomic number = 6, hybridisation = 2
Atom 2: atomic number = 17, hybridisation = 0
Atom 3: atomic number = 8, hybridisation = 2
Atom 4: atomic number = 6, hybridisation = 3
Atom 5: atomic number = 6, hybridisation = 3
Atom 6: atomic number = 6, hybridisation = 2
Atom 7: atomic number = 8, hybridisation = 2
Atom 8: atomic number = 17, hybridisation = 0
There are 2 acid chloride groups
The carbon atoms of the matches are: 1 6