Unix pipe and java program
Hi,
I want to make an utility that reads from a Unix pipe and prodouce an output to the screen. i.e. there is a "input.log" file to be processed as:
# tail -f input.log | java myprog | console
this time, "myprog" should take last few lines from "input.log" and process it in some way and prints the result to the shell.
Please suggest me possible solution.
Sumit
if you want to create your java program in such way that it could take input from pipe and produce output to pipe, then you actually have to get input ftom System.in and produce output to System.out
but what you mean by that | console after java myprog, that i don't understand...
actually, what you decribe to be your problem, could be solved with cat or furthermore, it could be solved with not touching anything...
since when you pipe progs together, then first progs output would be connected to seconds' input and so forth...
maybe this helps a bit...
Similar Messages
-
Hello everybody,
I'm trying to write a program that executes a perl script...
Process p = Runtime.getRuntime().exec("echo [email protected] | /root/bin/bulkmakemail");
it does not work
apparently exec() method does not know how to deal with UNIX pipe
or maybe it does but I don't uderstand how to make it work
can anybody help me?
thanks in advance
RomanHow about:
Process p = Runtime.getRuntime().exec(
"sh -c 'echo [email protected] |
| /root/bin/bulkmakemail'"
);Bingo. And to make this even more quote-mangling-proof, do this:
String[] args = new String[] {
"/bin/sh",
"-c",
"echo [email protected] | /root/bin/bulkmakemail"
... Runtime.getRuntime().exec(args);
This will prevent any problems with all those nested quotes getting mangled during the parse of the command line by the java runtime.
(Runtime.exec(String) has to be parsed by the java runtime itself so as to build the Unix exec() argv list - best to help it along yourself by calling Runtime.exec(String[]) instead). -
How to find cd rom drive in windows and unix platform using java program
Hi,
I am having the requirement of finding the cd rom drive
using java program. I do not know the label and which
one is the cd rom drive. also I want to know how many
cd rom drives are there on my system. I want the solution
for windows and unix platforms.
If have any suggestions please mail to [email protected]
DeepakUghhh.. I had the same problem with multi platform file-system detection
First off - Unix.
Do you know for sure you have all your drives mounted?? This could be a big problem because java will not see unmounted drives... So you can scour thru your /etc/fstab to find out which drives are available... or you can mount all and show roots... (Yuck!)... You've got timeouts and all sorts of things to worry about...
I would then shy away from the java.io.File.listRoots() on unix and rely on parsing your fs file. If a user would like to see the medium in the drive. Do a Runtime.exec and mount the drive, then you can grab the filesystem by wrapping it in the java.io.File object. ( NOTE - this will hold well for your NFS mounts as well which might be buried under other FS. So you now have detection for that as well. ) Labels are also noted in this file. Let me know if you don't know the difference between mtab and fstab....
Second - Winders.... Corney but I love saying that.
The listRoots is a good solution. As others have said CD-ROMS will not be writable. Use a combination of getName and getPath to decipher the label and mount point.
Hope this helps! -
Execute Unix command from Java program running on windows
Hello,
I need to write a java program that fetches file count in a particular unix machine directory. But java program will be running on windows machine.
The program should execute unix list command and fetch the output of that command.
Can anyone help me on this?
Thanks.Hi there,
I had a similiar problem, though years ago. It was to have a java program execute any other. Lately, I've had to have a java program running on a unix machine execute a shell script. Entirely two different scenarios. I'm not sure what you will need for your app, but look into this:
Java Native Interface for executing C/C++ code.
C/C++ Code for launching the program you need to run.
java.lang.Runtime(?).exec(....)
With a combination of that stuff, you can make a launcher for any os that has Java running on it, and with Runtime, you can exec() pretty near any sort of unix shell or app command you'd like.
Good luck.
Tim -
How to compile and execute lex,yac,c and java programs
its the 3rd day on my New MacBook pro..
as i just migrated from windows to mac i love to work on this..
The main problem is i DON't know .......
how to compile and execute
1) lex and yac programs
2) c program
3) java program
so please help me
THIS is the error i got a1.l is a program
i got the same error when i used gcc
$ lex a1.l
$ cc lex.yy.c
Undefined symbols:
"_yywrap", referenced from:
_yylex in cc8QDQjW.o
_input in cc8QDQjW.o
ld: symbol(s) not found
collect2: ld returned 1 exit statusIs the problem that you don't know how to compile and execute these programs on a Mac, or just that you don't know how to compile and execute them?
Mac OS X is really just a version of BSD Unix, as far as programs like like bison, flex and gcc are concerned...and even when Apple specific versions are provided in the Developer Tools, there are symlinks in the usual places in the Unix file hierarchy.
For problems with lex and yacc, I suggest you start with their own references, for example, here.
Or you could just use %option noyywrap, if you only have one file to scan.
Or you could link to libfl.a using -lfl and use the default version from that library.
But you really should (as Keith Barkley was subtly hinting at) learn how these tools work and why they work that way. -
Reg:Unix shellscripts running java programs
hi,
We are using unix shell scripts , by running that script it will execute some java programs.
when we running shell scripts, which executes the programs it is generating some log files ie some error is occuring.
i want to why these files are generating
Thanks and Regards,
Meer S.HI ,
we are running the shell script which runs java programs,
we are getting the result no problem ,
but it is generating the unwanted ORBTRC files
we are using websphere application server.
we donot want these orbtrc files.
HOW CAN WE DISABLE THE FILES
pls guide this.
Thanks and regards, -
Talking to Unix from Win32 Java program
Hi,
Im writing a program that is run in windows, but it needs to interface with a unix system. Is there any api's in java that will allow me to communicate with unix from a windows environment? I need to be able to send basic commands to the unix system from my program such as "cd dir" and "ls" and feed the output back to my program. I've had a look at the standard java.io package but this only lets me communicate with unix when the program itself is run from a unix environment. I would be grateful for any ideas.
Thankswell you can use "Socket/ServerSocket" class, if you want to send/recieve data it will work.....
I created a chat using that, one runs on Win32 and the other is on Unix..... -
Java plugin doesn't work, even though it's installed correctly and java programs work.
As stated. I have a link in ~/.mozilla/plugin that points to test/jre/plugin/i386/ns7/libjavaplugin_oji.so, which is the java 6 update 21 runtime environment.
Java doesn't show in about:plugins, and java applets don't start (firefox suggests to install missing plugins).
Java programs using the jre outside the browser work.
This is on Linux 32-bits, Slackware 13.0, kernel 2.6.34.<blockquote>As stated. I have a link in ~/.mozilla/plugin that points to test/jre/plugin/i386/ns7/libjavaplugin_oji.so, which is the java 6 update 21 runtime environment.
</blockquote>
Where did you read that?<br />
See http://kb.mozillazine.org/Java<br />
In Firefox 3.6 and later versions you need the Next-Generation Java™ Plug-In present in Java 6 U10 and later (Linux: libnpjp2.so; Windows: npjp2.dll).
http://java.com/en/download/faq/firefox_newplugin.xml
http://java.sun.com/javase/6/webnotes/install/jre/manual-plugin-install-linux.html
<pre><nowiki>ln -s /usr/local/java/jre1.6.0_20/lib/i386/libnpjp2.so libnpjp2.so
ln -s /usr/lib/jvm/jre/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/libnpjp2.so (java-1_6_0-sun-plugin)
</nowiki></pre> -
"at" UNIX Command in Java Program
Friends,
1. "at" command in UNIX execute Unix command at a scheduled time. 2. For each user there will be a table maintained internally which can be accessed by "at" with "-l" argument.
3. A mail will be sent to the owner with the output of the commands as a message.
I tried to run the "at" command of Unix in JSP, which gets succesfully executed in Oracle 10g App Server container (Installed in Solaris machine). I have tested the successful execution of command with the log file. But I haven't got any mail for the output. If anyone had any idea, please help me.
The code I have wtitten is
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(new String[] {"sh","-c","at 2115 Dec 7 < /export/home/usr1/abc.sh"});
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
logger.info("<ERROR>");
while ( (line = br.readLine()) != null)
logger.info(line);
logger.info("</ERROR>");
int exitVal = proc.waitFor();
logger.info("Process exitValue: " + exitVal);
My doubts are:
1. Who is the owner of the output of "at"command, which gets executed under Oracle 10g App Server container?
2. If no one is the owner, then where will the output of "at" command will go?
3. Is there any other way to execute "at" command of UNIX in java program? If so, then please help me.
Thanks in advance.
regards
Nandha Kumar.Mfilestream I have to ask - what's a chav ?
I have doubts abut what it is :-)
Seriously though, what is that an abbreviation for?
That's a new one to me.
http://www.chavscum.co.uk
chavs are roughly analogous to rednecksI wouldn't use that analogy. While both may lack certain social graces, rednecks typically don't receive ASBOs.
Chavs favor small cars with lots of bling whereas rednecks are likely to drive a pickup or a large sedan.
Chavs have pitbulls in their yards (gardens), rednecks an '84 Mustang LX on cinder blocks.
etc, etc.
Message was edited by:
filestream
Message was edited by:
filestream -
How to execute unix script in java program that is on unix .
hi ,
I want to call "sendfax" script that is for sending fax to Hylafax server.
This sendfax script is called in client java program.I want to call "sendfax" script that is for sending
fax to Hylafax server.
This sendfax script is called in client java program.And what is your problem? -
How communion between trigger and java program?
I want to achieve the effect:when data in database change ,the java program can know,but don't use refresh method?
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Jerry wang ([email protected]):
I want to achieve the effect:when data in database change ,the java program can know,but don't use refresh method?<HR></BLOCKQUOTE>
You can achieve that effect with oracle alert package.
Victor Batista
null -
Hello,
Do you know how to use Java Programming for BW, or what is the future of this solution? I do not know anything for the moment but I'm really interested in this connection.
Dou you know where I can find some documentation?
Everything could be helpfull for me.
Thank youHi Iuliana,
You can take a look at these links:
http://help.sap.com/saphelp_nw04/helpdata/en/6e/011e681cf74ab4b3acf73f77653405/content.htm
http://help.sap.com/saphelp_nw04/helpdata/en/d9/4a853bc623c075e10000000a114084/content.htm
Hope this helps... -
Executing Unix shell from Java Program
Hi,
I have written a java application using Maverick J2sshtools API which connects to a Unix box using SSH.The program authenticates with the remote box successfully,but It dosen't return the environment info or execute the test script.Have attached the complete code.
package shellInteraction;
import com.maverick.ssh.*;
import com.maverick.ssh2.Ssh2Client;
import com.maverick.ssh2.Ssh2Context;
import com.maverick.ssh2.Ssh2PasswordAuthentication;
import com.sshtools.net.*;
import java.io.*;
import java.util.Iterator;
import java.util.Vector;
public class JavaShell{
public static void main(String[] args) {
SshConnector con = null;
SshClient ssh = null;
ShellProcess process = null;
Shell shell = null;
try{
// Create a session to remote host
con = SshConnector.getInstance();
ssh = connectionSetup(con);
System.out.println(ssh);
// Start a session and do basic IO
if (ssh.isAuthenticated()) {
shell = new Shell(ssh);
System.out.println("Authenticated");
if(shell.getEnvironment().hasEnvironmentVariable("hostname"))
System.out.println("We are connected to " + shell.getEnvironment().getEnvironmentVariable("hostname"));
//System.out.println("Remote operating system is " + shell.getEnvironment().getOperatingSystem());
// boolean isWindows = shell.getEnvironment().getOSType()==ShellEnvironment.OS_WINDOWS;
//if(shell.getEnvironment().hasEnvironmentVariable("USERPROFILE")) {
//System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("USERPROFILE"));
//} else if(shell.getEnvironment().hasEnvironmentVariable("HOME")) {
//System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("HOME"));
// Commands only executed for Unix OS
//if(!isWindows) {
// Execute a script
traverseDirectory(shell);
shell.exit();
ssh.disconnect();
System.out.println("Shell has exited");
} catch(Throwable t) {
t.printStackTrace();
private static void traverseDirectory(Shell shell) throws Exception{
System.out.println("\n\nTraverse Directory");
// Execute a simple script than prints a directory tree
ShellProcess process = shell.execute("bash test.sh ");
try{
process.expect("Total directories", 1000, true);
System.out.print(process.toString());
} catch (ShellTimeoutException ex1) {
System.out.println("TRAVERSE Expect operation timed out. Sending interrupt to kill the process");
process.interrupt();
}finally {
process.close();
static private Ssh2Client connectionSetup(SshConnector con)throws SshException{
Ssh2Client ssh = null;
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Hostname: ");
String hostname = reader.readLine();
int idx = hostname.indexOf(':');
int port = 22;
if(idx > -1) {
port = Integer.parseInt(hostname.substring(idx+1));
hostname = hostname.substring(0, idx);
System.out.print("Username [Enter for " + System.getProperty("user.name") + "]: ");
String username = reader.readLine();
if(username==null || username.trim().equals(""))
username = System.getProperty("user.name");
System.out.println("Connecting to " + hostname);
* Create an SshConnector instance
con = SshConnector.getInstance();
// Lets do some host key verification
HostKeyVerification hkv = new PasswordHostKey();
con.setSupportedVersions(SshConnector.SSH2);
* Set our preferred public key type
con.getContext(SshConnector.SSH2).setHostKeyVerification(hkv);
((Ssh2Context)con.getContext(SshConnector.SSH2)).setPreferredPublicKey(Ssh2Context.PUBLIC_KEY_SSHDSS);
* Connect to the host
ssh = (Ssh2Client)con.connect(new SocketTransport(hostname, port), username, true);
* Authenticate the user using password authentication
Ssh2PasswordAuthentication passwordAuthentication = new Ssh2PasswordAuthentication();
System.out.print("Password: ");
passwordAuthentication.setPassword(reader.readLine());
if(ssh.authenticate(passwordAuthentication)!=SshAuthentication.COMPLETE) {
System.out.println("Authentication failed!");
System.exit(0);
}catch(Exception ex1) {
throw new SshException(ex1.getMessage(), ex1.getCause());
return ssh;
When I execute the program
Hostname:****
Username [Enter for thaya]: **
Connecting to CATL
The connected host's key (ssh-dss) is
b6:85:91:6b:8b:ea:cb:40:b5:6f:01:2e:66:78:7f:62
Password: *****
SSH2 CATLMSXP62:22 [kex=diffie-hellman-group1-sha1 hostkey=ssh-dss client->server=aes128-cbc,hmac-sha1,none server->client=aes128-cbc,hmac-sha1,none]
Authenticated
Traverse Directory
com.maverick.ssh.ShellTimeoutException: The shell did not return to the prompt in the given timeout period 10000ms
at com.maverick.ssh.Shell.A(Unknown Source)
at com.maverick.ssh.Shell.execute(Unknown Source)
at shellInteraction.ShellInteraction.traverseDirectory(ShellInteraction.java:108)
at shellInteraction.ShellInteraction.main(ShellInteraction.java:68)
This is the error message what i get.use code tags if you want a response,
ive done the same thing once using
ssh2.ethz.ch ie:
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ServerHostKeyVerifier;
import ch.ethz.ssh2.Session;
the code looked something like this:
try
conn.connect(new ServerHostKeyVerifier() {
public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
return true;
conn.authenticateWithPassword(username, password);
try {
sess = conn.openSession();
} catch (java.lang.IllegalStateException e) {
return;
// JOptionPane.showMessageDialog(null, "Could not autheticate.\nCheck username and password.\nTerminating.", "Authentication Failed", JOptionPane.ERROR_MESSAGE);
// System.exit(-1);
sess.requestPTY("dumb", 50, 50, 0, 0, null);
sess.startShell();
}and after that sess has getStdIn() and getStdOut() that get the streams from which you read and write. -
.bat files and java program
I know that I have posted something just like this before, but I just can't get this to work. I want to have my application call a .bat file and execute it. Can anyone please supply me some code (maybe just a small program) that executes a .bat file from within the program itself. This would be very helpful. I just can't get it to work at all.
To open notepad in a windows system:
import java.io.*; // Needed for IOException
public class Notepad
public static void main(String[] args)
try
Runtime.getRuntime().exec("notepad");
catch (IOException ioExc)
System.out.println("Something has gone horribly wrong!");
Notes:
1) notepad is usually in the path system variable. You will probably have to type in the entire path to the .bat file you want to execute.
2) The .exec(programName) will block until the program is terminated.
3) You are losing any semblance of system independance by doing this. -
Unable to excute unix command from java program
import java.io.File; // is java code
public class RunSystemCommand {
public static void main(String args[]) {
String s = null;
// system command to run
String cmd = "ls ";
// set the working directory for the OS command processor
File workDir = new File("c:/cygwin/cygwin");
Process p = Runtime.getRuntime().exec(cmd, null, workDir);
p.waitFor();
I am tryiing to excute above code to run unix command on cygwin but gave folllowing error...... but works well to open a note pad..
Exception in thread "main" java.io.IOException: CreateProcess: C:/cygwin/bin err
or=5
at java.lang.Win32Process.create(Native Method)
at java.lang.Win32Process.<init>(Unknown Source)
at java.lang.Runtime.execInternal(Native Method)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at d.main(d.java:19)
It seems using this functionone cannot excute unix commands..please help to do so..Are you sure you want cygwin/cygwin?
the following works fine for me, you may need change the workDir to your bin folder
import java.io.File; // is java code
import java.io.InputStream;
public class RunSystemCommand {
public static void main(String args[]) throws Throwable {
String s = null;
// system command to run
String cmd = "ls ";
// set the working directory for the OS command processor
File workDir = new File("c:/cygwin/bin");
Process p = Runtime.getRuntime().exec(cmd, null, workDir);
InputStream pis = p.getInputStream();
while( pis.read() != -1 ); // added, as otherwise the ls hangs.
p.waitFor();
}
Maybe you are looking for
-
Hello, I feel like this is something simple but I cannot write a correct script to do it. How would I write a script that just gets the urls of all tabs in safari? then if one exists, it selects that tab to be opened.
-
DW CS5.5 and Yosemite [subject edited by moderator]
i upgraded to a new computer with Yosemite, after migrating my settings over. Adobe CS5.5 works fine except Dreamweaver CS 5.5, it says it is unable to locate menus.xml and cannot rebuild from a backup. It suggests reinstalling. But when i try to rei
-
Lightroom 5: strange import preset
Since I have updated to LR 5 I have the problem that all imported files are automatically colored blue and rated with 4 stars. Is this possibly some sort of preset I can switch off? Thank you very much in advance for your assistance! Greetings Eike
-
Hi In make-to-order scenario after doing CO15 the sales order stock for raw material is not removed in MMBE. But finished product is updated in sales order. In CO15 what are the movement type i have to use. How to solve this. Thanks Mani
-
I made this drop-down navigational menu for my website and am trying to insert it inside my DIV tag. There are two parts to the script. The first part you put inside the HEAD, the second part goes into the body. However, I want to be able to drag and