Java Reference
In-Depth Information
ments. It throws an LSFailedException if the command completed unsuc-
cessfully:
// We have imported java.io.* and java.util.*
public String[] ls(String dir, String opts)
throws LSFailedException
{
try {
// start up the command
String[] cmdArray = { "/bin/ls", opts, dir };
Process child = Runtime.getRuntime().exec(cmdArray);
InputStream lsOut = child.getInputStream();
InputStreamReader r = new InputStreamReader(lsOut);
BufferedReader in = new BufferedReader(r);
// read the command's output
List<String> lines = new ArrayList<String>();
String line;
while ((line = in.readLine()) != null)
lines.add(line);
if (child.waitFor() != 0) // if the ls failed
throw new LSFailedException(child.exitValue());
return lines.toArray(new String[lines.size()]);
} catch (LSFailedException e) {
throw e;
} catch (Exception e) {
throw new LSFailedException(e.toString());
}
}
In the ls method we want to treat the output as character data, so we
wrap the input stream that lets us read the child's output through an
InputStreamReader . If we wanted to treat the child's output as a stream
of bytes, we could easily do that instead. If the example were written to
use the second form of exec , the code would look like this:
 
Search WWH ::




Custom Search