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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

}<br />

}<br />

if (line == null)<br />

break;<br />

nLines++;<br />

System.out.println(nLines + ":" + line);<br />

If there is a way to run a java program by just typing the name in UNIX. I mean<br />

instead of typing for example "java Main" just type "Main" and run the program. And<br />

how to implement that in a makefile?<br />

Answer: Write a script that runs the program and put it in your path. For<br />

instance:<br />

#!/bin/sh<br />

java BlahBlah<br />

Call this whatever you want, mv it to your /usr/local/bin directory, then just type it at<br />

the command line and BlahBlah will be run.<br />

Q: Are there any <strong>Java</strong> libraries for executing Linux commands?<br />

Answer: Try java.lang.Runtime.exec(). E.g.<br />

Runtime.getRuntime().exec("xterm");<br />

Note if you want to use shell builtins or shell features like<br />

redirection you need a shell, e.g.:<br />

Runtime.getRuntime().exec(new String[] {"/bin/sh",<br />

"-c", "ls / 2>&1 | tee ls.log"});<br />

I'd like to know how to know which operating system java application is running<br />

on.<br />

Answer: You could try using the system Properties.<br />

e.g.<br />

Properties prop = System.getProperties();<br />

String osString = prop.getProperty( "os.name" );<br />

I would like to know how my <strong>Java</strong> program can catch when someone sends a<br />

"kill" to my app in Unix or does a Ctrl-C in windows?<br />

In Unix there is atexit() function that handles this type of situation. Is this possible in<br />

<strong>Java</strong> ?<br />

Answer: Starting with 1.3 there is Runtime.addShutdownHook(). This is for cleanup<br />

only.<br />

from API: "A shutdown hook is simply an initialized but unstarted thread. When the<br />

virtual machine begins its shutdown sequence it will start all registered shutdown<br />

hooks in some unspecified order and let them run concurrently. When all the hooks<br />

have finished it will then run all uninvoked finalizers if finalization-on-exit has been<br />

enabled.<br />

Finally, the virtual machine will halt. Note that daemon threads will continue to run<br />

file:///F|/350_t/350_tips/os_win_linux.htm (4 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!