4.1 Using OEChem oemolstreams

The previous example demonstrated reading and writing SMILES strings from the command line. This requires the programmer to perform the I/O explicitly. While this may be reasonable for SMILES strings that can be read on a single line, it is unsuitable for more complex file formats. To ease this task, OEChem provides the "molstream" abstraction. The classes oemolistream and oemolostream allow input and output of molecules from files or strings.

The first interface to stream I/O uses functions to read and write molecules. This is provided by the functions OEReadMolecule and OEWriteMolecule that both take a molstream and a OEMolBase as arguments. As a high-level function OEReadMolecule calls mol.Clear() automatically for each incoming molecule.

 1 /**************************************************************
 2  * Copyright 2005, OpenEye Scientific Software, Inc.
 3  *************************************************************/
 4
 5 import openeye.oechem.*;
 6
 7 public class MolstreamRead1 {
 8   public static void main(String argv[]) {
 9     oemolistream ifs = new oemolistream();
10     oemolostream ofs = new oemolostream();
11
12     OEGraphMol mol = new OEGraphMol();
13     while (oechem.OEReadMolecule(ifs, mol)) {
14       oechem.OEWriteMolecule(ofs, mol);
15     }
16   }
17 }
18

Listing:4.1 High-level molecule i/o using molstreams

In this example, the script will read molecules from stdin in SMILES format and write them to stdout in (absolute) SMILES format. Notice that in this example, there's no need to call the Clear method to reset the molecule, or OEAssignAromaticFlags to normalize aromaticity. This is done automatically by the OEReadMolecule method.

To read molecules and put them into a Java container...

 1 /**************************************************************
 2  * Copyright 2005, OpenEye Scientific Software, Inc.
 3  *************************************************************/
 4
 5 import java.util.ArrayList;
 6 import java.util.Iterator;
 7
 8 import openeye.oechem.*;
 9
10 public class MolListRead {
11   public static void main(String argv[]) {
12     oemolistream ifs = new oemolistream(argv[0]);
13     oemolostream ofs = new oemolostream();
14
15     ArrayList mollist = new ArrayList();
16
17     // read molecules and put copies into list
18     OEGraphMol mol = new OEGraphMol();
19     while (oechem.OEReadMolecule(ifs, mol)) {
20       OEGraphMol listMol = new OEGraphMol(mol);
21       System.out.println(listMol.GetTitle());
22       if (listMol.IsValid())
23         mollist.add(listMol);
24     }
25
26     System.out.println(mollist.size()+" molecules loaded.");
27
28     // loop over list and output
29     for (Iterator iter = mollist.iterator(); iter.hasNext();) {
30 	  oechem.OEWriteMolecule(ofs, (OEGraphMol)iter.next());
31     }
32   }
33 }
34
35

Listing:4.2 Reading molecules into a list