Running perl programs through java.

How do i run a perl program through java?
arg.pl :
while(<STDIN>)
print;
java program that I tried:
import java.io.*;
class runtime
    static Process p;
    static BufferedReader stdOutput;
    static BufferedWriter stdInput;
    public static void main(String args[]) throws IOException
        int i = 0;
        try{
            String cmd[] = new String[] {"perl","arg.pl"};
            p = Runtime.getRuntime().exec(cmd,null,new File("./"));
            stdOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            stdInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        catch(Exception ex){
            System.out.println("Unable to initiate Process : " + ex);
        stdInput.write("abcd\n");
        stdInput.write("1234\n");
        stdInput.write("efgh\n");
        stdInput.write("5678\n");
        stdInput.close();
        System.out.println(stdOutput.readLine());
        System.out.println(stdOutput.readLine());
        System.out.println(stdOutput.readLine());
        System.out.println(stdOutput.readLine());
}This works well. But I need to read the output line by line as and when i give the standard input line by line to it.
I tried the following :
import java.io.*;
class runtime
    static Process p;
    static BufferedReader stdOutput;
    static BufferedWriter stdInput;
    public static void main(String args[]) throws IOException
        int i = 0;
        try{
            String cmd[] = new String[] {"perl","arg.pl"};
            p = Runtime.getRuntime().exec(cmd,null,new File("./"));
            stdOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            stdInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        catch(Exception ex){
            System.out.println("Unable to initiate Process : " + ex);
        stdInput.write("abcd\n");
        stdInput.flush();
        System.out.println(stdOutput.readLine());
        stdInput.write("1234\n");
        stdInput.flush();
        System.out.println(stdOutput.readLine());
        stdInput.write("efgh\n");
        stdInput.flush();
        System.out.println(stdOutput.readLine());
        stdInput.write("5678\n");
        stdInput.flush();
        System.out.println(stdOutput.readLine());
        stdInput.close();
}This doesn't work well. It just halts without any output.
Can anyone help me?
Edited by: Vijayakrishna on Dec 5, 2007 8:30 AM

Let me be more specific.
I want to use a class which will look something like this.
import java.io.*;
public class FindAnswer{
    Process p;
    BufferedReader stdOutput;
    BufferedWriter stdInput;
    public FindAnswer()
        try{
            String cmd[] = new String[] {"perl","arg.pl"};
            p = Runtime.getRuntime().exec(cmd,null,new File("./"));
            stdOutput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            stdInput = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        catch(Exception ex){
            System.out.println("Unable to initiate Process. Error: " + ex);
    public String getAnswer(String question)
        String answer = question;
        try{
            stdInput.write(question + System.getProperty("line.separator"));
            stdInput.flush();
            answer = stdOutput.readLine();
        catch(Exception ex){
            System.out.println("Exception. Error: " + ex);
        return answer;
    public void close()
        if (p != null) {
            try {
                if (p.getInputStream() != null)
                    p.getInputStream().close();
                if (p.getOutputStream() != null)
                    p.getOutputStream().close();
                if (p.getErrorStream() != null)
                    p.getErrorStream().close();
            catch (Exception e) {
                System.out.println("Exception in Closing Streams - " + e);
}The perl program takes lot of initialization time. I dont want to run the program foreach question i have. I'll just create an object to this class and find and answer by passing question to the object's getAnswer method. Here, I dont know all the questions in the beginning itself. I'll know one by one only and I should find answer without terminating the process.
Kindly help me in this.

Similar Messages

  • How to run windows program through java applications.

    pls help me!!!!! code RED!~

    C:\Documents and Settings\student\Desktop\Running.java:12: cannot resolve symbol
    symbol : variable JMStudio
    location: class Running
    String path="C:/Program Files/MF2.1.1/bin"+JMStudio;
    ^
    1 error
    this error is generated
    any idea on how to solve it?

  • Error while running executable file through java in WinNT

    I would like to run an executable file with Java.
    - If I try with notepad or paint, i.e. Windows Applications,
      I have no problem.
    - I also can run Non-Windows-Own Applications, except one.
      I get an error message, if I want to run this program through Java.
    I have tried following commands to run an executable file.
    Runtime.getRuntime().exec("cmd.exe /c "+command);
    Runtime.getRuntime().exec("cmd.exe /c start "+command);
    Runtime.getRuntime().exec("cmd.exe /c start /wait "+command);
    Runtime.getRuntime().exec("cmd.exe /k start "+command);
    command : the path to the executable file
    I can run the application directly, if I click the icon on desktop,
    but not through Java.
    here is the error message I get
    screenshot : http://www.aykut.de/error_message.jpg
    Text : "Security Check failure"
            The Logon System has been tampered with.
            The Administrator will need to re-install.
    my Idea :
    The application is "old".
    I think it was written for Win 3.1.
    Therefore I don't know if there is any other
    possibilty to run a "DOS Exe File" through Java.

    I have just figured out how it works,
    if somebody else here in forum have this problem,
    here is the solution :
    String path = "F:\...\...\Application.exe";
    String envDir = path.substring(0, path.lastIndexOf("\\"));
    String[] command = {"cmd.exe", "/c", "start", "/wait", "/D"+envDir, path};
    Process process = Runtime.getRuntime().exec(command);
    "start /Dpath" => path: environment directory F:\...\...\
    "start /wait" => wait until Application.exe terminates
    if you use Win95 or Win98 use command.com instead of cmd.exe
    Aykut

  • How to run Perl script in Java program?

    Some say that the following statement can run Perl script in Java program:
    Runtime.getRuntime().exec("C:\\runPerl.pl");
    But when I run it, it'll throw IOException:
    java.io.IOException: CreateProcess: C:\runPerl.pl error=193
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:63)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:566)
    at java.lang.Runtime.exec(Runtime.java:428)
    at java.lang.Runtime.exec(Runtime.java:364)
    at java.lang.Runtime.exec(Runtime.java:326)
    at test.runPerl.main(runPerl.java:16)
    Exception in thread "main"
    Where is the problem? In fact, I do have a Perl script named "runPerl.pl" in my C:/ directory. Could anybody tell me why it can't be run? Thanks in advance.

    Hello sabre,
    First of all thanks for your reply.
    I have tried like what you mentioned.
    Eventhough, i could get the exact error message.
    I could get the Exception
    "Exception:java.lang.IllegalThreadStateException: process hasn't exited"
    <code>
    import java.io.*;
    public class Sample{
    public static void main(String args[]) {
    String s = null;
    Process p;
    try
         p = Runtime.getRuntime().exec("tar -vf sample.tar");
         //p.waitFor();
         if(p.exitValue() == 0)
              System.out.println("CommandSuccessful");
         else
              System.out.println("CommandFailure");
    catch(Exception ex)
         System.out.println("Exception:"+ex.toString());
    </code>
    In this code, i tried to run the "tar command". In this command i have given -vf instead -xvf.
    But it is throwing
    "Error opening message catalog 'Logging.cat': No such file or directory
    Exception:java.lang.IllegalThreadStateException: process hasn't exited
    CommandFailure"
    "Error opening message catalog 'Logging.cat'" what this line means ie,
    I dont know what is Logging.cat could you explain me its urgent.
    Thanks in advance.
    Rgds
    tskarthikeyan

  • How to run native program with Java program?

    Hello
    I've got following problem. I'd like to write file browser which would work for Linux and
    Windows. Most of this program would be independent of the system but running programs not. How to run Linux program from Java program (or applet) and how to do it in Windows?.
    Cheers

    Try this:
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("ls -l");
    InputStream stream = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stream);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    while ( (line = br.readLine()) != null) .....
    "if the program you launch produces output or expects input, ensure that you process the input and output streams" (http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html)

  • Run Perl script in JAVA

    Can we run perl scripts in java, still supporting perl API?
    Thanks a lot for help!

    I haven't tried it but I think 6.0 supports some
    scripting.But NOT perl!Sorry, I didn't mean some Perl Scripting. I meant some scripting and I wasn't sure what languages.

  • I want to do rpc programming through java how can i do it?

    i want to do rpc programming through java how can i do it? any classes for it? i am not goin to use rmi its an assignment for us in syllabe help is strongly needed

    So, you are in a class. You are a student, your job is to learn something. Unless your instructor has failed horribly in his/her duty, then you are failing in your duty as a student.
    Your lack of even trying hurts me personally as a life-long student, I find your post ill-advised.
    Please, do not post to these forums anymore. Thank you.

  • Running Program through Java

    I want to write java program :-
    That java program run a exe file.
    I give a input file for that exe file.
    the output write in text file.

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Running cmd commands through java

    Hi,
    I am trying to run few dos commands through java using Runtime.exec("command") but I am getting following error
    commmand is cd D:\CodeMerge\A\
    java.io.IOException: CreateProcess: cd.. error=2
    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 createDirectory.main(createDirectory.java:24)
    Basically what I am looking for is this:
    1) My program is in D:\Amit\RM
    2) I want to get out to D:\ go to CodeMerge\A\.
    3) Create folder with curretn date as name of the folder
    Hence I am doing
    rTime.exec("cd../..");
    rTime.exec("cd D:\CodeMerge\A\");
    rTime.exec("mkdir "+date);
    Can anybody tell me why I am getting this error
    Jounty

    U can run either DOS Commands or UNIX Commands thru the following Java Program
    Written By BalaNagaraju Malisetti
    contact: [email protected]
    import java.io.*;
    public class RunBdiff
    public static String rununixcmd(String v_prev_path,String v_curr_path,String v_delta_path,String v_beg,String v_len)
    String s = null;
    FileOutputStream fos;
    DataOutputStream dos;
    try
    int v_int_beg = Integer.parseInt(v_beg);
    int v_int_len=Integer.parseInt(v_len);
    int v_int_end=(v_int_beg+v_int_len)-1;
    String v_pos1=String.valueOf((v_int_beg+2));
    String v_pos2=String.valueOf((v_int_end+2));
    String cmd1 = "bdiff ";
    String cmd2=v_prev_path;
    String cmd3=" ";
    String cmd4=v_curr_path;
    String cmd5="| grep '^>'";
    String cmd6="| cut -c";
    String cmd7=v_pos1+"-"+v_pos2;
    String cmd8="| sort ";
    String cmd9="| uniq ";
    String cmd=cmd1+cmd2+cmd3+cmd4+cmd5+cmd6+cmd7+cmd8+cmd9;
    String[] commands = {"/bin/csh","-c",cmd}; //in Unix
    //String[] commands = {"cmd.exe","-c",cmd}; //in Windows
    Process p = Runtime.getRuntime().exec(commands);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    // read the output from the command
    File file = new File(v_delta_path);
    fos = new FileOutputStream(file);
    dos=new DataOutputStream(fos);
    //Writing the output of bdiff command to Delta File
    while ((s = stdInput.readLine()) != null)
    dos.writeChars(s);
    //Return Error Message to Calling Procedure
    while ((s = stdError.readLine()) != null)
    return s;
    return s;
    catch (IOException e)
    return String.valueOf(e);
    public static void main(String args[])
    String msg=rununixcmd("/home/g_anil/MS_ADDRESS1.dat","/home/g_anil/MS_ADDRESS2.dat","/home/g_anil/MS_ADDRESS_DELTA.dat","1","9");
    **************************************************************************************************************************************

  • Problems running external programs from java

    Hello.
    I wrote a pair of perl scripts and a GUI in java to run them. The first perl script just read the files in one directory makes some changes to the names of the files and then group all this files in a set of new directories. The other perl scripts takes all this new files and calls BLAST sequence alignment program and perform some alignments among these sequences. I tested this scripts and they work fine.
    The problem comes when I try to run them for the JAVA GUI. I use RunTime and when I need to run the first perl script it all works well, but when The call to the second perl script is made the program fisishes without doing anything at all. I found out that the problem is that when running the script from the Java GUI it's not able to find BLAST program. So I guess that Java is not really starting a terminal session and it doesn't read my bash_profile to find out the path to my programs.
    So, my question is if anyone knows a method to tell Java to load all this paths in the bash_proflie file so all of my scripts work???.
    I have no idea is this can be done and how so any advice would be really wellcome.
    By the way, my java version is 1.4.2 and my OS is Mac OS X 10.3
    Thanks a lot , Julio

    Invoke /bin/sh -c and give it your program's full path with.
    (To understand what I've written, maybe reading
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps_p.html
    http://mindprod.com/jgloss/exec.html
    and
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html
    (especially the exec(String[] cmdarray) method)
    might help)
    -T-

  • Running Unix command through Java

    Hi
    I am trying to run the unix command "rf filename" through Java and it doesnt seem to work.
    Can anyone help in this case please
    String cm = "rm ";
    String delFile =  args[0];        // this path is /data/temp/filename.doc
    Process p = Runtime.getRuntime.exec(cmd +delFile);Also since i dont have access to delete the file through my login i always login as root for a few commands.
    Is there a way i can specify user name & password & then run the command?
    Please let me know
    Thanx

    Please discard the above msg i got a solution by just adding file.delete
    thanx

  • How to compile and run package programs in Java

    Hi,
    I want to know how to compile and run the package programs in Java using -d. instead of creating the package folder manually.
    eg:
    package Test;
    class test1
    public void disp()
    //Any code;
    I want to compile this without creating the folder ' Test ' manually. that is if we use -d with javac the Test folder will be created automatically. I need the format of -d
    could anyone please help me.
    Thanks in Advance ,
    Ambika

    My program Test.java in F:\Tomcat5\webapps\Ambika\WEB-INF\Classes. I compiled in the format below. I got like this. What should I do for this? But yesterday I compiled like this only, It compiled and the folder com\cert\Test.class is created. Today again I compiled the pgm after deleting the already created folder 'com\cert', I got the error like this.
    I've given my pgm and the thing I've got when I compiled it.
    Test.java
    package com.cert;
    public class Test
         public void display()
              System.out.println("Hai");
    F:\Tomcat5\webapps\Ambika\WEB-INF\Classes>javac -d F:\Tomcat5\webapps\Ambika\WEB-INF\Classes\Test.java
    javac: no source files
    Usage: javac <options> <source files>
    where possible options include:
    -g Generate all debugging info
    -g:none Generate no debugging info
    -g:{lines,vars,source} Generate only some debugging info
    -nowarn Generate no warnings
    -verbose Output messages about what the compiler is doing
    -deprecation Output source locations where deprecated APIs are u
    sed
    -classpath <path> Specify where to find user class files
    -cp <path> Specify where to find user class files
    -sourcepath <path> Specify where to find input source files
    -bootclasspath <path> Override location of bootstrap class files
    -extdirs <dirs> Override location of installed extensions
    -endorseddirs <dirs> Override location of endorsed standards path
    -d <directory> Specify where to place generated class files
    -encoding <encoding> Specify character encoding used by source files
    -source <release> Provide source compatibility with specified release
    -target <release> Generate class files for specific VM version
    -version Version information
    -help Print a synopsis of standard options
    -X Print a synopsis of nonstandard options
    -J<flag> Pass <flag> directly to the runtime system
    F:\Tomcat5\webapps\Ambika\WEB-INF\Classes>
    Plz help me.
    thanks in advance
    Ambika

  • Why i get error msg when i run my program? (java.lang.NoClassDefFoundError)

    i have compile and run my program. First time the program can run. But after that when i run, come out error messege as below:
    java.lang.NoClassDefFoundError: FormPoster (wrong name: search/FormPoster)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)
    Exception in thread "main"
    what can i do? thank very much

    Hello,
    i have compile and run my program. First time theprogram can run.
    But after that when i run, come out error messegeas below:
    java.lang.NoClassDefFoundError: FormPoster (wrongname: search/FormPoster)
    Check your FormPoster class: the classname has to be
    the same as
    the file name and the class should be stored in its
    correct directory
    (the sub directory structure should reflect the
    package name).
    kind regards,
    JosYou should also check your clsspath if you are using packages.

  • Problem in running Perl script through oracle

    Hi,
    I am facing one problem in perl script.
    " I have one perl script which is interact with sybase database.We have migrated the sybase database to oracle successfully.Now i wanna to change the perl script to interact with oracle database.
    I am using the code like that for interacting the oracle database
    Old Code with sybase database : use DBI::Sybase::GFAS;
    New code with oracle database : Use DBI::oracle::GFAS;
    When i am running the perl script,Its showing the below mentioned error:
    Can't locate DBI/oracle.pm in @INC (@INC contains: C:\oracle\product\10.2.0\db_1
    \perl\5.8.3\lib\MSWin32-x86 C:\oracle\product\10.2.0\db_1\perl\5.8.3\lib/MSWin32
    -x86-multi-thread C:\oracle\product\10.2.0\db_1\perl\5.8.3\lib C:\oracle\product
    \10.2.0\db_1\perl\5.8.3\lib\MSWin32-x86 C:\oracle\product\10.2.0\db_1\perl\site\
    5.8.3 C:\oracle\product\10.2.0\db_1\perl\site\5.8.3\lib/MSWin32-x86-multi-thread
    C:\oracle\product\10.2.0\db_1\perl\site\5.8.3\lib C:\oracle\product\10.2.0\db_1
    \sysman\admin\scripts C:/Perl/lib C:/Perl/site/lib .) at hello.pl line 4.
    BEGIN failed--compilation aborted at hello.pl line 4.
    Anyone have any idea about this error.
    Thx in advance.

    If you look in the oracle home in the perl\site\5.8.3\lib\MSWin32-x86-multi-thread directory you will see two directories. Once is DBI and one is DBD.
    All you need in your perl program is a line 'use DBI'. It will use DBD automatically as and when required. You can specify the necessary connection information when you issue the DBI->connect statement.
    I have successfully managed to connect to Oracle databases and perform DML using the software installed by default. You don't need to download and install anything else.
    I'm no perl expert so maybe some functionality is missing using the interfaces provided by Oracle but for my needs it has sufficed.
    Hope this helps.

  • Run a program from java code

    I want to run this program from my java code,
    In Linux(ubuntu) I write this command to open the program window
    $ paraFoam -case /home/saud/OpenFOAM/OpenFOAM-1.5/run/tutorials/icoFoam/cavity/In my java code I wrote it like this("/home/saud/OpenFOAM/OpenFOAM-1.5/bin/" is the path of the program):
    String command = "/home/saud/OpenFOAM/OpenFOAM-1.5/bin/paraFoam " +
              "-case /home/saud/OpenFOAM/OpenFOAM-1.5/run/tutorials/icoFoam/cavity/";
    final Process myProcess = Runtime.getRuntime().exec(command);
    BufferedReader buf = new BufferedReader(new InputStreamReader(
              myProcess.getInputStream()));
    String line;
    while ((line = buf.readLine()) != null) {
         System.out.print(String.format("%s\t\n", line));
    buf.close();
    int returnCode = myProcess.waitFor();
    System.out.println("Return code = " + returnCode); Return code = 0
    but the program is not opening
    Edited by: Saud.R on Apr 11, 2009 3:37 AM

    Welcome to the Sun forums.
    I am not sure of the answer to your question, but people who use Processes regularly, warn other users to ensure they are also doing something with the error stream of the process, otherwise it can hang as you describe.

Maybe you are looking for

  • Problem with dual boot after upgrade to Mountain lion

    Hello Every One, I have a Macbook pro from 2009 which had dual boot option Windows 7 + Snow Leopard. The windows 7 had 2 partitions (C; and D: an extended partition). I upgraded the OS X to Mountain lion. after upgrade the system showed 3 options at

  • Ordinary java class and jsp page

    hi i want to use some java class(not javabean ) in my jsp . how do i import them and use them?

  • Mini Displayport - DVI - HDMI 5V?

    I kind of have an odd setup desire for an external display. I want to send video and audio to my entertainment unit from my MBP across the room. I already have audio sorted out (mini optical -> 30ft optical cable), but the video is a bit more difficu

  • "Document can't be opened."

    "Document can't be opened."  Appears when I try to open Pages documents.  I listen with access to documents on iPhone 5, I edit them at same time on ipad 2.  Issue began after trip to FL upon return docs would not open.  I ise icloud to save my docum

  • SIDADM do not have enough previlages to startsap after DB2 upgrade to 9.5

    Hello Anyone, I recently upgrade our DB2 version from 8.X to 9.5.2, We run SAP netweaver ECC 5  with DB2.  I can startsap if I do db2start and and then issue a startsap after su to sidadm. Please can anyone advice I had followed all instruction of th