4.3 Molecule Input and Output with Files

In addition to stdin and stdout, OEChem's oemolstreams also support reading from files. To open a file, use the filename as a constructor argument or call the open method with the filename as an argument. For input (oemolistream) if the file doesn't exist, the open fails and returns false. For output (oemolostream) the output file is created if it didn't previously exist and is overwritten if it did. If no filename is passed as an argument to the constructor (or to the open method), an oemolistream will use stdin and an oemolostream will use stdout. oemolstreams can be closed after use with the close method. When an oemolstream goes out of scope and is deleted by Java, it is automatically closed as well.

 1 /**************************************************************
 2  * Copyright 2005, OpenEye Scientific Software, Inc.
 3  *************************************************************/
 4 import openeye.oechem.*;
 5
 6 public class FileInputOutput {
 7   public static void main(String argv[]) {
 8     oemolistream ifs = new oemolistream();
 9     oemolostream ofs = new oemolostream();
10
11     if (ifs.open("drugs.sdf") && ofs.open("drugs.mol2")) {
12       OEGraphMol mol = new OEGraphMol();
13       while (oechem.OEReadMolecule(ifs, mol)) {
14         oechem.OEWriteMolecule(ofs, mol);
15       }
16     }
17     else {
18       System.err.println("Unable to open input or output file.");
19     }
20   }
21 }

Listing:4.4 Reading and writing from files

One convenient use of the open method of molstreams is that it sets the file format associated with the stream from the file extension of the filename used as the argument. The example above converts the file "drugs.sdf" in MDL SD format into the file, "drugs.mol2" in Tripos Mol2 format. This behavior can be overridden by calling SetFormat after the call to open but before the first molecule is read or written from/to the stream.