Running a shell script through java

Hi all,
I have a simple question here.
How can I run a shell script through java and put the text output into a string.
I'd be very grateful if you could show me sample code...
Have a great day,
Pesho

Runtime.exec()
There are plenty of examples. Read the following before continuing, however, as it will save alot of headaches:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Similar Messages

  • Running Unix Shell scripts through Java

    How to run Unix shell scripts through Java program ?

    Use:
    Process p = Runtime.getRuntime().exec("sh script.sh");Then you can use:
    p.getOutputStream and read the output of your program.

  • Running Shell scripts through JAva

    Hi,
    I tried to execute a Shell script through a Java program.
    The code I used is as below:
    import java.lang.*;
    import java.io.*;
    public class sys {
    public static void main(String[] args) {
    Runtime rt = Runtime.getRuntime();
    String[] callAndArgs = { "chgpasswd" };
    try {
    Process child = rt.exec(callAndArgs);
    child.waitFor();
    System.out.println("Process exit code is: " + child.exitValue());
    catch(IOException e) {
    System.err.println( "IOException starting process!");
    catch(InterruptedException e) {
    System.err.println( "Interrupted waiting for process!");
    The "chgpasswd" shell script calls the "passwd" command of Unix.
    It threw out an IO exception.
    Then I gave the parameter as "./chgpasswd". It now gave an exit value of 255.
    The "chgpasswd" script exists in the same directory as the .class file.
    I checkd up the exit code reference...it says exit value of 255 could mean as exit code out of range........an exit code > 255....which unfortunately has no documentation, I guess.
    Can you help ?

    This is on a Unix platform, correct? Assuming so...
    If I remember correctly, exit codes can be greater than 255. To get the real exit code equates to something like: exitcode & 512 to obtain the real exit code.
    Make sure "chgpasswd" shell script has the execute permissions set. Additionally, make sure that the first line of the script (the magic line) has the appropriate shell/interpreter to execute specified. For example, if "chgpasswd" were a Bourne (sh) script, the first like would be:
    #!/bin/shFor perl, it may be something like:
    #!/usr/bin/perlIt needs to be the absolute path to the shell/interpreter is the point.

  • How to run unix shell script from java web applet

    hi all
    i have created one java applet. my apache web server is on unix server.
    i have created one shell script in same directory where my .class and .htm files reside...
    how to run this shell script from applet? it should search this .sh file on server and not on the client browser machine...
    thanks in advance

    I suppose you could make the shell script into a CGI, configure the server to execute CGIs, and then make the applet open the URL of that CGI.

  • Run a .sh script through JAVA ?

    Hi All,
    I have a shell script that basically gives me some status on my UNIX box. The name of the script is "scstat". But I need to parse the output shown by this script using JAVA.
    Does anybody know of any code or let me know the ways to implement this......your help is appreciated.
    Best Regards, sangita

    Test with string "ls -al", etc..
    import java.io.DataInputStream;
    import java.io.IOException;
    * Created on Apr 26, 2004
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    * @author root
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class Execute {
         public static void main(String[] args) {
              Execute ex = new Execute();
              ex.execute("./scstat.sh" );     //if in current directory, need the path.
         /**Returns the output
          * @param string
         public static String execute(String string) {
              Process p;
              String s = null;
              try {
                   p = Runtime.getRuntime().exec(string);
              //     p.waitFor();
              DataInputStream in = new DataInputStream(p.getInputStream());
              while ( (s=in.readLine())  !=  null){
                   System.out.println(s);
              } catch (IOException e) {
                   e.printStackTrace();
              return s;
    }

  • How do i print parameters in shell script through java

    Hi,
    I am sorry if have posted this query in wrong thread!!!
    How do i print the parameter in shell script which are passed from java programm?
    i have tried in different ways.. but the actual param value is not printing when i execute the java programm
    java code is here
    import java.io.IOException;
    public class TestShell {
          * @param args
    public static void main(String[] args) {
             String inputFilePath=args[0];
              String inputFileName=args[1];
              String outputFileName=args[2];
              String outputFilePath=args[3];
              Runtime r = Runtime.getRuntime();
              String[] cmdArray = new String[]{"Test.sh",inputFilePath, inputFileName, outputFileName, outputFilePath};
              try {
                   r.exec(cmdArray);
                   System.out.println("Test.sh executed successfully.");
              } catch (IOException e) {
                   e.printStackTrace();
    }I need a shell script to print paramenters (inputFilePath, inputFileName, outputFileName, outputFilePath)
    Thanks,
    Jasmin

    user13836688 wrote:
    But my code is something look like thisWell unless I've completely lost my marbles (possible) or Java Runtime.exec() does something I've never heard of, I can't even see how that will execute. For a start, assignments in the Bourne shell take the form ofinfile = $inputFilename;orinfile = "inputFilename";not what you've got; and the first form would only work if you've set the appropriate environment variables.
    Are you sure you're not confusing this with a Javascript script?
    Winston
    Edited by: YoungWinston on Apr 18, 2011 12:51 PM
    And BTW, you don't need to put ';' at the end of each statement, unless there's more than one on a line.
    Edited by: YoungWinston on Apr 18, 2011 12:54 PM
    BTW2: 'printf "%d", inpath' also looks very dodgy, since 'inpath' is unlikely to be a number (in fact, it's unlikely to be anything).
    I think you might want to get a book on scripting.

  • How to invoke a shell script using java

    Hi
    I am trying to invoke a shell script(unix) using java and I have tryied to load the shell using exec(cmd) and then trying to execute the shell.
    But it is not working.
    Can you please guide me on this matter.

    Hi I am facing the same problem
    I want to call a shell script through java in linux system of course.
    I am using the following section of code .
    public class LinuxServer {
         public static void main(String args[]){
              Runtime r = Runtime.getRuntime(); //get runtime information
              try
              Process Child = r.exec("/usr/bin/ksh") ; //execute command
              BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(Child.getOutputStream()));
              outCommand.write("/opt/jboss-4.0.0/test1.sh");
              outCommand.flush();
              try
              Child.waitFor(); //wait for command to complete
              catch(InterruptedException e)
              { //handle waitFor failure
              System.out.println("ERROR: waitFor failure");
              System.exit(10); //exit application with exit code 10
              catch(IOException e)
              { //handle exec failure
              System.out.println("ERROR: exec failure"+e);
              System.exit(11); //exit application with exit code 11
    But when I am compiling and running this script in the linux system,
    Its giving the following error.
    Exception in thread "main" java.lang.NoClassDefFoundError: while resolving class: LinuxServer
    at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.initializeClass() (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at gnu.gcj.runtime.FirstThread.run() (/usr/lib/libgcj.so.5.0.0)
    at JvThreadRun(java.lang.Thread) (/usr/lib/libgcj.so.5.0.0)
    at JvRunMain(java.lang.Class, byte const, int, byte const, boolean) (/usr/lib/libgcj.so.5.0.0)
    at __gcj_personality_v0 (/opt/jboss-4.0.0/java.version=1.4.2)
    at __libc_start_main (/lib/tls/libc-2.3.4.so)
    at JvRegisterClasses (/opt/jboss-4.0.0/java.version=1.4.2)
    Caused by: java.lang.ClassNotFoundException: java.lang.StringBuilder not found in [file:/usr/local/staf/lib/JSTAF.jar, file:/usr/local/staf/samples/demo/STAFDemo.jar, file:/home/db2inst4/sandip/staf/lib/JSTAF.jar, file:/home/db2inst4/sandip/staf/samples/demo/STAFDemo.jar, file:/usr/share/java/libgcj-3.4.3.jar, file:./, core:/]
    at java.net.URLClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at gnu.gcj.runtime.VMClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.ClassLoader.loadClass(java.lang.String, boolean) (/usr/lib/libgcj.so.5.0.0)
    at JvFindClass(_Jv_Utf8Const, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
    at JvBytecodeVerifier.verify_instructions_0() (/usr/lib/libgcj.so.5.0.0)
    at JvVerifyMethod(_Jv_InterpMethod) (/usr/lib/libgcj.so.5.0.0)
    at JvPrepareClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at JvWaitForState(java.lang.Class, int) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.linkClass0(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
    ...9 more
    Pls help

  • Running Shell Scripts within Java code!!!

    Hi,
    How do I run a shell script from my Java code???
    Also I need to ensure my next line of Java code is executed only after the shell script has finished executing.
    Since my shell script just cuts out some line for a txt file and then only my Java code parses the cut-out file section and processes certain info.
    Please help!!!
    Thanks!!!

    Runtime.exec and, if you need your Java to stop until the external executable is complete, Process.waitFor.
    And you'll want to read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Executing shell script through PL/SQL

    Hi,
    I need some help regarding execution of shell script through Oracle PL/SQL.
    I have a shell script present in /abc/xyz folder with name search.sh , Through a PL/SQL procedure I am creating a file to store the report data.
    I want to execute /abc/xyz/search.sh from the PL/SQL procedure to delete all files created before 3 mins .
    1.     At first I took Java route and got following permissions granted for RECON user.
    GRANT USER SYS java.io.FilePermission <<ALL FILES>> execute ENABLED 351
    GRANT USER SYS java.lang.RuntimePermission readFileDescriptor * ENABLED 350
    GRANT USER SYS java.lang.RuntimePermission writeFileDescriptor * ENABLED 349
    2.     Then I created a simple java class for execution of OS command as below
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "OSCommand" AS
    import java.io.*;
    import java.util.*;
    public class OSCommand{
    public static String Run(String Command){
    try{
    Process proc = Runtime.getRuntime().exec(Command);
    int ext=proc.waitFor();
    return ("0");
    catch (Exception e){
    System.out.println("Error running command: " + Command +
    "\n" + e.getMessage());
    return(e.getMessage());
    3.     And a wrapper function as below to use this class
    create or replace
    FUNCTION OSCommand_Run(Command IN STRING)
    RETURN VARCHAR2 IS
    LANGUAGE JAVA
    NAME 'OSCommand.Run(java.lang.String) return int';
    4.     In my PL/SQL proceedure I am using following code to execute the command
    v_Return := OSCommand_Run('/abc/xyz/search.sh');
    to execute the shell script.
    Proceedure executes without any error and generates a new csv file with report data , however shell script does not get executed and hence all csv files created earlier remain as it is in the folder.
    Please help.

    Sven W. wrote:
    What happens if you remove the catch exception block from your java command?
    I asume you still might have a permission issue. But it could be hidden from you, because of the exception is catched and printed into nirvana.Executed the wrapper function OSCOMMAND_RUN as below
    DECLARE
    v_Return VARCHAR2(2000);
    BEGIN
    v_Return := OSCOMMAND_RUN('/recon/html/invoice/search.sh' );
    DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
    END;
    And following is the result
    v_Return = 0
    Process exited.
    In case of exception it would had printed the exception.
    One more thing I noticed, even though I have taken following permissions
    GRANT     RECON     SYS     java.io.FilePermission     /abc/*     execute     ENABLED     347
    GRANT     RECON     SYS     java.io.FilePermission     /abc/xyz/*     execute     ENABLED     351
    GRANT     RECON     SYS     java.io.FilePermission     <<ALL FILES>>      execute     ENABLED     352
    GRANT     RECON     SYS     java.lang.RuntimePermission     readFileDescriptor     *     ENABLED     350
    GRANT     RECON     SYS     java.lang.RuntimePermission     writeFileDescriptor     *     ENABLED     349
    When I create a new search.sh in /abc dir I get following error
    v_Return = the Permission (java.io.FilePermission /abc/search.sh execute) has not been granted to RECON. The PL/SQL to grant this is dbms_java.grant_permission( 'RECON', 'SYS:java.io.FilePermission', '/abc/search.sh', 'execute' )
    Edited by: 960702 on Sep 25, 2012 10:34 AM

  • Exceuting SQL Script through java

    Hi All
    I am making an installer for my application. How do i execute a SQL script through java. Its a sepeate file that has the SQL script for DB creation.
    Regards
    Abhinav

    If you database support ";" to separate sqll, then you can use Statement.execute(sql); to run all SQLscipt once, otherwise you need to load all sqls into Vector, then reun sql step by step. Copy some code for instance:
    public final static Object[] getSQLStatements(String sqlFile) throws java.
    io.IOException {
    java.util.Vector v = new java.util.Vector(1000);
    try {
    java.io.BufferedReader br = new java.io.BufferedReader(new java.io.
    FileReader(sqlFile));
    java.util.Vector batchs = new java.util.Vector(10);
    String temp;
    while ( (temp = br.readLine()) != null) {
    temp = temp.trim();
    if (temp.length() == 0)
    continue;
    switch (temp.charAt(0)) {
    case '*':
    case '"':
    case '\'':
    // System.out.println(temp);
    break; //Ignore any line which begin with the above character
    case '#': //Used to begin a new sql statement
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    break;
    case 'S':
    case 's':
    case '?':
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    v.addElement(temp);
    break;
    default:
    batchs.addElement(temp);
    break;
    if (batchs.size() > 0) {
    v.addElement(getSQLStatements(batchs));
    batchs.removeAllElements();
    br.close();
    br = null;
    catch (java.io.FileNotFoundException fnfe) {
    v.addElement(sqlFile); //sqlFile is a sql command, not a file Name
    Object[] statements = new Object[v.size()];
    for (int i = 0; i < v.size(); i++)
    statements[i] = v.elementAt(i);
    return statements;
    for (int i = 0; i < statements.length; i++) {
    if (statements[i] instanceof java.lang.String) {
    String temp = (java.lang.String) statements;
    switch (temp.charAt(0)) {
    case 'S':
    case 's':
    case '?':
    System.out.println(temp);
    rs = stmt.executeQuery(temp);
    ResultSetMetaData resultSetMetaData = rs.
    getMetaData();
    int iNumCols = resultSetMetaData.getColumnCount();
    for (int j = 1; j <= iNumCols; j++) {
    System.out.println(resultSetMetaData.getColumnLabel(j)
    + " " + resultSetMetaData.getColumnTypeName(j)
    + " " + resultSetMetaData.getColumnType(j)
    + " " + resultSetMetaData.getPrecision(j)
    + " " + resultSetMetaData.getScale(j)
    Object colval;
    long ncount = 0;
    while (rs.next()) {
    // System.out.print(rs.rowDeleted()+" ");
    ncount++;
    for (int j = 1; j <= iNumCols; j++) {
    colval = rs.getObject(j);
    System.out.print(colval + " ");
    System.out.println();
    rs.close(); //Let the CONCUR_UPDATABLE resultSet release its open files at once.
    rs = null;
    System.out.println(
    "The total row number of resultset: " + ncount);
    System.out.println();
    break;
    default:
    int updateCount = stmt.executeUpdate(temp);
    System.out.println(temp + " : " + updateCount);
    System.out.println();
    else if (statements[i] instanceof java.lang.Object[]) {
    int[] updateCounts;
    Object[] temp = (java.lang.Object[]) statements[i];
    try {
    for (int j = 0; j < temp.length; j++){
    System.out.println( temp[j]);
    stmt.addBatch( (java.lang.String) temp[j]);
    updateCounts = stmt.executeBatch();
    for (int j = 0; j < temp.length; j++)
    System.out.println((j+1)+":"+temp[j]);
    for (int j = 0; j < updateCounts.length; j++)
    System.out.println((j+1)+":" +updateCounts[j]);
    catch (java.sql.BatchUpdateException e) {
    updateCounts = e.getUpdateCounts();
    for (int j = 0; j < updateCounts.length; j++)
    System.out.println((j+1)+":"+updateCounts[j]);
    java.sql.SQLException sqle = e;
    do {
    System.out.println(sqle.getMessage());
    System.out.println("Error Code:" +
    sqle.getErrorCode());
    System.out.println("SQL State:" + sqle.getSQLState());
    sqle.printStackTrace();
    while ( (sqle = sqle.getNextException()) != null);
    catch (java.sql.SQLException sqle) {
    do {
    System.out.println(sqle.getMessage());
    System.out.println("Error Code:" +
    sqle.getErrorCode());
    System.out.println("SQL State:" + sqle.getSQLState());
    sqle.printStackTrace();
    while ( (sqle = sqle.getNextException()) != null);
    stmt.clearBatch();
    System.out.println();

  • Trying to run Power shell Script on task schedule

    My case is i'm trying to run a power shell script through the task schedule.
    Note if i run the script locally it is working fine but from the task schedule it is not working.
    More information: 
    script function: Password Change Notification
    Task name : test3
    Time to do the task: 9:08 am every day
    the status : running 
    .ps1 file location: under C\windows\system32\
    some actions in the task history after the dated time to run:
    1 Task Scheduler launched "{3023b1eb-9b29-47b9-ace2-e6083e2f00cc}"  instance of task "\test3" due to a time trigger condition
    2 Task Engine "S-1-5-21-60622444-1628707926-2526327935-500: enviroment\Admin:S4U:LUA"  received a message from Task Scheduler service requesting to launch task "\test3" .
    3 Task Scheduler started "{3023b1eb-9b29-47b9-ace2-e6083e2f00cc}" instance of the "\test3" task for user "enviroment\admin
    4 Task Scheduler launched action ""C:\Windows\System32\Password Change Notification\Password Change Notification.ps1"" in instance "{3023b1eb-9b29-47b9-ace2-e6083e2f00cc}" of task "\test3
    5 Task Scheduler launch task "\test3" , instance "C:\Windows\System32\notepad.exe"  with process ID 5052

    Hi MeipoXu,
    First of all i would like to thank you for your answer, i followed the URL that you posted already in the previous comment and unfortunately it didn't work, and please find my ps1 file
    content as typed below and give me your feedback on that.
    #  # Version 1.1 May 2014
    # Robert Pearman (WSSMB MVP) # TitleRequired.com
    # Script to Automated Email Reminders when Users Passwords due to Expire.
    # # Requires: Windows PowerShell Module for Active Directory
    # # For assistance and ideas, visit the TechNet Gallery Q&A Page. http://gallery.technet.microsoft.com/Password-Expiry-Email-177c3e27/view/Discussions#content
    # Please Configure the following variables....
    $smtpServer="outlook. myDomain " $expireindays = 7
    $from = "الدعم الفني
    <ITHelpDesk@myDomain>"
    $logging = "Enabled" # Set to Disabled to Disable Logging
    $logFile = "PassExpireNotlog.csv" # ie. c:\mylog.csv
    $testing = "Enabled" ## "Enabled" # Set to Disabled to Email Users
    $testRecipient = "MyEmail@MyDomain"
    $encoding = [System.Text.Encoding]::Unicode $date = Get-Date -format ddMMyyyy
    # Check Logging Settings if (($logging) -eq "Enabled")
    {     # Test Log File Path
        $logfilePath = (Test-Path $logFile)     if (($logFilePath) -ne "True")
        {         # Create CSV File and Headers
            New-Item $logfile -ItemType File
            Add-Content $logfile "Date,Name,EmailAddress,DaystoExpire,ExpiresOn,MsgBody"
        } } # End Logging Check
    # Get Users From AD who are Enabled, Passwords Expire and are Not Currently Expired
    Import-Module ActiveDirectory $users = get-aduser -filter * -SearchScope Subtree -SearchBase "OU=UsersOU,DC=MyDomain,DC=MyrootDomain,DC=MYrootNS" -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet,
    EmailAddress |where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }
    $maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
    # Process Each User for Password Expiry foreach ($user in $users)
    {     $Name = (Get-ADUser $user | foreach { $_.Name})
        $emailaddress = $user.emailaddress
        $passwordSetDate = (get-aduser $user -properties * | foreach { $_.PasswordLastSet })
        $PasswordPol = (Get-AduserResultantPasswordPolicy $user)
        # Check for Fine Grained Password
        if (($PasswordPol) -ne $null)     {
            $maxPasswordAge = ($PasswordPol).MaxPasswordAge
        $expireson = $passwordsetdate + $maxPasswordAge
        $today = (get-date)     $daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days
                 # Set Greeting based on Number of Days to Expiry.
        # Check Number of Days to Expiry
        $messageDays = $daystoexpire     if (($messageDays) -ge "2")
        {         $messageDays = "خلال
    " + "$daystoexpire" + " ايام"
        }     elseif (($messageDays) -eq "2")
        {         $messageDays = "خلال يومين
        }     else
        {         $messageDays = "اليوم."
        }     # Email Subject Set Here
        $subject="كلمة المرور الخاصة بك ستنتهي
    $messageDays"
           # Email Body Set Here, Note You can use HTML, including Images.
        $body =     "<P style='font-family: Arial; font-size: 16pt' />
        <center> الاستاذ/ $name
    </center> 
        <br>     <center>
    كلمة المرور الخاصة بك ستنتهي $messageDays </center>
        <br>     <center>
    نأمل تغييرها في أقرب فرصة حتي تتمكن من الدخول على النظام
    </center>
        <br>     <center>
    مع تحيات الادارة العامة لتقنية المعلومات
    </center> 
        <br>     </P>"
            # If Testing Is Enabled - Email Administrator
        if (($testing) -eq "Enabled")
        {         $emailaddress = $testRecipient
        } # End Testing     # If a user has no email address listed
        if (($emailaddress) -eq $null)
        {         $emailaddress = $testRecipient    
        }# End No Valid Email     # Send Email Message
        if (($daystoexpire -ge "0") -and ($daystoexpire -lt $expireindays))
        {          # If Logging is Enabled Log Details
            if (($logging) -eq "Enabled")
            {             Add-Content $logfile "$date,$Name,$emailaddress,$daystoExpire,$expireson,$body" 
            }         # Send Email Message
            Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High -Encoding $encoding
                    } # End Send Message
      } # End User Processing
    # End

  • Passing long string to shell script from java

    I am trying to passa a long string to a shell process through java,
    call is like
    Runtime rtime = Runtime.getRuntime();
    String callAndArgs[] = {"/apps/jetty4/jstest/jstest.sh",jarCo,queue,text};
    Process child = rtime.exec(callAndArgs);
    here the string text is :
    |HEADER|JAR933|[email protected]|290001|OL0006528|WIN4015444|SHAFT_FORGING|1.0|Baan EDM|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
    |290001|WIN4015444|00||||2|SHAFT FORGING|9|AXELSMIDE|3|ACHSE SCHMIEDEST�CK|4|ARBRE FORG�|f|AKSELITAOS|||||||||||||||||||||||No||Approved|41.0|Mechanic|Yes|pc||WIN4015444|EL20|Purchased|Metric||0|20051120|||||Released||||||||||||||||No||||||||||||||||||||||||||||||||
    Now i use this string in shell script to pass as an argument to other class. But the string gets truncated.
    How do i solve this?

    It appears that your os is truncating the data - Java's not involved.
    Maybe write the data to a file and then read it into the external program some way.

  • Secure login to remote UNIX host and run a shell script

    Hi I am new to JAVA. I want to login to remote UNIX host from my application secure login (SSH) and run a shell script reside that remote host. Can any one let me know the way how to do it. If possible provide the code example.

    Runtime.exec with an ssh command (not really recommended).
    Much better, an SSH API (JSch, which needs JZlib, from http://www.jcraft.com/ is a good one).

  • Invoking Shell Script from JAVA Stored procedure

    I am trying to invoke shell script using Java Stored procedure.
    When I run my java class outside of oracle using oracle user
    account it works but as soon as i load it into database and try
    to inovoke that class using PL/SQL wrapper it runs java class
    but is not able to invoke the shell script. Any ideas would be
    greatly appreciated.

    Pleass search the forums for "runtime" as there are many threads and examples already posted.

  • Invoking a bash shell script from Java code

    Hi All
    I am trying to invoke a Bash shell script using java code. The arguments required are "source wmGenPatch <source dir> <destination dir> no_reverse.
    in the code I have specified the arguments considering the cannonical paths of the files as the code may run on Unix or windows platform.
    I am getting a error while invoking Runtime.getRuntime().exec(args). The error is as follows :
    "The Error Occurred is: CreateProcess: source D:\Package4.0\workspace\DiffEngineScripts\v4a02\wmGenPatch D:\Package4.0\workspace\fromImageFilesDir\ D:\Package4.0\workspace\toImageFilesDir\ no_reverse error=2"
    It seems that error=2 indicates that the 'file not found' exception. But i can see the directories referred to in the error at place in the workspace.
    Kindly advice.
    Thanks in advance.

    Hi All
    I am pretty new to invoking bash shell scripts from java and not sure if i am progressing in right direction.
    The piece of code tried by me is as follows
    try {
                   currentDir = f.getCanonicalPath();
              } catch (IOException e) {
              if (currentDir.contains("/")) {
                   separator = "/";
              } else {
                   separator = "\\";
              String args[] = new String[7];
              args[0] = "/bin/sh";
              args[1] = "-c";
              args[2] = "source";
              args[3] = currentDir + separator + "DiffEngineScripts" + separator
                        + "v4a02" + separator + "wmGenPatch";
              args[4] = sourceFileAdd;
              args[5] = destFileAdd;
              if (isReverseDeltaRequired) {
                   args[6] = "reverse";
              } else {
                   args[6] = "no_reverse";
              try {
                   Process xyz = Runtime.getRuntime().exec(args);                              
                   InputStream result = xyz.getInputStream();
                   InputStreamReader isr = new InputStreamReader(result);
                   BufferedReader br = new BufferedReader(isr);
                   String line = null;
                   while ( (line = br.readLine()) != null)
                        System.out.println(line);
                   int exitVal = xyz.waitFor();
                   System.out.println("Leaving Testrun.java");
              } catch (Throwable t) {
                   t.printStackTrace();               
    and on running the same i am getting Java.io.IOException with the stack trace
    java.io.IOException: CreateProcess: \bin\sh -c source D:\Package4.0\workspace\DiffEngineScripts\v4a02\wmGenPatch D:\Package4.0\workspace\fromImageFilesDir\ D:\Package4.0\workspace\toImageFilesDir\ no_reverse error=3
    kindly advice
    Thanks in advance

Maybe you are looking for

  • Open Other Project Feature Follow up ?

    I just posted a question in regards to "Open Other Project" button giving me inconsistent results. I was reading other posts to try to find an answer when something I read made me question myself. When I am setting "Open Other Project" as an option,

  • New internal hard drive not recognized at all!

    Hello everybody! I really need your help. I tried to upgrade my internal 120gb drive to a Western Digital wd2500bevs. But when I start my Macbook with the Leopard DVD neither the System Profiler nor the Disk Utilities Program recognize the drive for

  • New itunes, no old itunes. How do I put the music on my ipod onto my itunes

    I recently had my computer cleaned out. When they clean it out, they clean it out. They ended up having to remove my music folders to clean it out. How can I put the music on my ipod onto my new itunes? Is there a way I can do this? Thank you.

  • How to read and image file in a BLOB database filed

    I'm using Oracle Reprots 10g I have a database filed of type BLOB ( that can be BMP, GIF, JPG, PDF ..etc .. it can be any format/extension) From Oracle Reports how I can display this image file

  • First ever Web Form - URL error

    Hi. I'm attempting to call my first Web form, but I'm getting this error: URL: http://springfield01:7777/forms/frmservlet?config=ttmsmenu ERROR: 500 Internal Server Error Forms Servlet Error. Missing or invalid value for baseHTML parameter. Please ch