27.04.2013 Views

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Operational Systems & <strong>Java</strong><br />

that printout was broken into two pices by another printouts? I mean for example if<br />

you do:<br />

In 1st thread: System.out.println("1234567890");<br />

And in 2nd thread: System.out.println("something else here");<br />

it never will be broken like:<br />

12345<br />

something else here<br />

67890<br />

Even if Sun didn't write about it explicitly, we can see that it is synchronized or at<br />

least behaves like synchronized that is the same for our real life.<br />

How can I pass a string to the command line(DOS) ? Also i want to capture the<br />

output given by the command line in a string.<br />

Answer: Try this out:<br />

// works for DOS<br />

String cmds[] = new String[2];<br />

cmds[0] = "dir"; // replace with "ls" on UNIX<br />

cmds[1] = "c:"; // replace with "/" on UNIX<br />

// execute the command<br />

Process pro = Runtime.getRuntime().exec(cmds);<br />

// wait until it's done executing<br />

pro.waitFor();<br />

// what did the process output from the Input pipe back to<br />

// this process (okay, who named this stuff)?<br />

InputStream out = pro.getInputStream();<br />

// output it (really slowly)<br />

int i;<br />

while ((i = out.read()) != -1) System.out.println((char) i);<br />

How can I take a program that runs in a DOS shell and send the text that comes<br />

from the shell program into a <strong>Java</strong> program where it can analyzed, etc.?<br />

Answer: From a command line, use a pipe (with the "|" symbol):<br />

c:\> dosprogram | java <strong>Java</strong>Program<br />

In the <strong>Java</strong> program, read the text from System.in:<br />

public static void main(String[] args) throws IOException {<br />

int nLines = 0;<br />

BufferedReader in =<br />

new BufferedReader(<br />

new InputStreamReader( System.in));<br />

for (;;) {<br />

String line = in.readLine();<br />

file:///F|/350_t/350_tips/os_win_linux.htm (3 of 8) [2002-02-27 21:18:56]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!