Runtime.exec--problems writing to external file

Hi. I went to http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html, and am still quite confused regarding the use of Runtime.exec, for my purposes. I want to decompile a CLASS file using javap, and then write that to a TXT file, for easier reading/input to JAVA. Now, I use the following code (a modification of what I got from http://www.mountainstorm.com/publications/javazine.html, as the "traps" article's sample code is WAY too confusing--they say the compiler had the output sent to text.txt, without even showing how in the source code they did that), but it hangs up. Modifications to the string array cause different results, such as showing the javap help menu, or saying that the class wasn't found, but I think the way I did the array here is right:
import java.util.*;
import java.io.*;
public class Test {
        try {
         String ls_str;
            String[] cmd = {"C:\\j2sdk1.4.2_04\\bin\\javap", "-c", "-classpath", "H:\\Java\\metricTest", "metricTest > blah.txt", ""};
            Process ls_proc = Runtime.getRuntime().exec(cmd);
         // get its output (your input) stream
         DataInputStream ls_in = new DataInputStream(
                                          ls_proc.getInputStream());
         try {
          while ((ls_str = ls_in.readLine()) != null) {
              System.out.println(ls_str);
         } catch (IOException e) {
          System.exit(0);
     } catch (IOException e1) {
         System.err.println(e1);
         System.exit(1);
     System.exit(0);
}

Also, jesie, I realize that's what I need...the only
problem is, the name "test.txt" is nowhere to be found
in the source code! lolLooks like I have to explain this, then.
When you look at a Java program you'll notice that it always has a "main" method whose signature looks like this:public static void main(String[] args)When you execute that program from the command line, it takes whatever strings you put after the class name and passes them to the main program as that array of strings. For example if you run it likejava UselessProgram foo bar hippothen the "java" command takes the three strings "foo", "bar", and "hippo" and puts them into that args[] array before calling the "main" method.
That means that inside the "main" method in this case, "args[0]" contains "foo", "args[1]" contains "bar", and "args[2]" contains "hippo".
Now go back to the example and see how it lines up with that.

Similar Messages

  • Runtime.exec not releasing lock on files

    Hi,
    I am using Runtime.exec to launch an external application, a batch file that runs a java program and generates a pdf file on disk. The Runtime.exec is called from inside the callback function of a toolbar button in my UI. Once, the runtime.exec returns, I popup a alert saying "pdf generated successfully". However, when I try to open the pdf that has been generated, I get a message saying the "program is in use by another program" or some such message. Only when I quit my GUI application, Iam able to open the pdf file using acrobat reader.
    Can someone tell me how to solve this problem. I have tried doing proc.waitFor() etc.
    Cheers,
    vidyut

    You can try some of sysinternals tools to look through file sharing information and decide what process is locked file.
    PS Try to ensure that you start java in same process as batch file executes, overthise you just can't ensure it terminates on time.

  • Runtime exec problem with command "start"

    L.S,
    I'm working on a webservice client for uploading
    and downloading files. When a file is downloaded, it
    should be opened by the appropriate application. I
    know that this is -in theory- possible by issuing a
    start command through Runtime.getRuntime.exec():
    public void doSomething(String realName, DataHandler handler) {
      File outFile = new File(realName);
      FileOutputStream out = new FileOutputStream(outFile);
      handler.writeTo(out);
      out.close();
      String fileName = outFile.getAbsolutePath();
      Process p = Runtime.getRuntime().exec("start " + fileName);
    }Running this on my Win2000 system with J2RE 1.4.2 consistently
    fails with this message:
    java.io.IOException: CreateProcess: start C:\tmp\test.pdf error=2When I issue the exact same command from a DOS shell, Adobe
    starts up with the test document loaded. I now believe that my own
    application is somehow 'holding on to' the file, preventing an
    external application like Adobe from consuming the same file.
    Does anyone know how I can get around a problem like this? How do
    I start the appropriate application and feed it the file that was
    just downloaded by the user?

    I did a search for Runtime.exec and found some good help in this forum. Someone posted something like the following and it works pretty well.
    <<begin code>
    // Determine proper shell command (extend per OS)
    String os_name = System.getProperty("os.name");
    String shellParam "";
    if (os_name.startsWith("Windows"))
    if ( (System.getProperty("os.name").endsWith("NT")) ||
    (System.getProperty("os.name").endsWith("2000")) ||
    (System.getProperty("os.name").endsWith("XP")) )
    shell = "cmd.exe";
    } else
    shell = "command.com";
    shellParam = "/C";
    // Create a string with your program executable
    String command = "myprogram.exe";
    // Create an array of each command, I found that placing "cmd.exe /c"
    // in the same string doesn't work.
    String[] cmd_array = new String[] {
    shell,
    shellParam,
    command
    Runtime.getRuntime().exec( cmd_array );
    <<end code>>
    Do a java API search for Runtime.exec (if you use Eclipse right click and hit Open Declaration) there are ways to invoke exec that support setting of the environment as well as the current directory.

  • Java.lang.Runtime.exec problem in ubuntu 9.10

    Hi:
    I tried to run some command in the java code , for example "grass64 -text /home/data/location", this command works well in the terminal, however when I call it in the java code I got some excepetions.
    My code is :
    public class Grass {
         public static String grassBatJob="GRASS_BATCH_JOB";
         public void run(String cmd,String jobPath) {
              //set the environments variables
              Map<String, String> env=new HashMap<String, String>();
              env.put(grassBatJob, jobPath);
              String gisDataBase="/home/kk/grass/GrassDataBase";
              String location="spearfish60";
              String mapset="PERMANENT";
              cmd=cmd+" "+gisDataBase+"/"+location+"/"+mapset;
              CommandLine line=new CommandLine(cmd);
              //the real cmd should be >>grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT
              System.out.println("start line=="+line.toString());
              DefaultExecutor de=new DefaultExecutor();
              try {
                   int index=de.execute(line,env);
                   System.out.println(index);
              } catch (ExecuteException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              String jobPath=Grass.class.getResource("grass.sh").getFile();
              new Grass().run("grass64 -text", jobPath);
    The real cmd I want to execute is "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT" with the envrionment variable "GRASS_BATCH_JOB=jobPath",it works well in the ternimal ,however in my application I got the exception"
    java.io.IOException: Cannot run program "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT": java.io.IOException: error=2, No such file or directory
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
         at java.lang.Runtime.exec(Runtime.java:593)
         at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:58)
         at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:246)
         at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:302)
         at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:149)
         at org.kingxip.Grass.run(Grass.java:27)
         at org.kingxip.Grass.main(Grass.java:38)
    Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
         at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
         at java.lang.ProcessImpl.start(ProcessImpl.java:65)
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
         ... 7 more
    I wonder why?

    Thanks for all of your reply, and now I can run the command, however I met some problems when I tried to get the result of the exec.
    The core codes are shown below:
    String cmd="g.version";
    String[] exe={"bash","-c",cmd};
    Process p1=Runtime.getRuntime.exec(exe,env); // the env has been set
    GrassThread outThread=new GrassThread("out", p1.getInputStream());
    outThread.start();
    GrassThread errorThread=new GrassThread("error", p1.getErrorStream());
    errorThread.start();
    int exitVal = p1.waitFor();
    String resu=outThread.sb.toString();
    System.out.println("==========the output start========");
    System.out.println(resu);
    System.out.println("==========the output end========");
    System.out.println("ExitValue: " + exitVal); //------------------> line one
    public class GrassThread extends Thread{
         public StringBuffer sb=new StringBuffer();
         public GrassThread(String type,InputStream is) {
              this.type=type;
              this.is=is;
         public void run() {
              try {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader br = new BufferedReader(isr);
                   String line = null;
                   while ((line = br.readLine()) != null) {
                        System.out.println(type + ">" + line);
                        sb.append(line).append("\r");  // ----------------------------> line two
    }I define a StringBuffer in the GrassThread to save the output (see the code where I marked by "line two"), and when the process complete, I check the StringBuffer to get the output (see code where I marked by "line one"), however the output in the console of the IDE are :
    ----------- output in the console of the IDE start -------------
    ==========the output start========
    ==========the output end========
    ExitValue: 0
    out>GRASS 6.4.0RC5 (2009)
    ----------output in the console of the IDE end--------------------
    I can not understand, in the code "line one", I first get the output using "System.out.println(resu);",then I print the exitvalue,but why the order of the output in the console is not what I expected?
    Another question, the code above assume the output can be got from the Process's getInputStream, however sometimes the output maybe come from the Process's getErrorStream, so how to handle it?
    Edited by: apachemaven on 2010-3-5 ??5:38

  • Runtime.exec  problems

    Hi
    I would like to open a chm file from my "help" menu.
    I got two problem related to that:
    1.The first time the menu is clicked i start the process and the help is opened on top of my application frame.
    but - the second time It is opened - the only wat to recognize i sthe process is still active is to call exitValue (if it get an exception - process is still active) but - how can i make the frame on top of my application frame( the current active frame)
    2.when the application is closed the help application does not "die" with the rest of the application.
    I will be happy to get some ideas of how can i control it.
    this is my code:
    Runtime runtime=  Runtime.getRuntime();
            try {
                if(process==null){
                     process=runtime.exec(new String[] {"cmd.exe","/c" , helpLink});
                else{
                    try {
                        process.exitValue();
                        process = runtime.exec(new String[]{"cmd.exe", "/c", helpLink});
                        if (log.isDebugEnabled())
                            log.debug("process finish working");
                    } catch (IllegalThreadStateException e1) {
                        if (log.isDebugEnabled())
                            log.debug("process still working");
            } catch (IOException e1) {
                if (log.isErrorEnabled()){
                    log.error("could not open help file"+ helpLink);
                    log.error("exception:",e1);
                WorkingAreaManager.getWorkingAreaManagerInstance().displayErrorMessage(COULD_OPEN_HELP);
            }thanks,Liat

    1.The first time the menu is clicked i start the
    process and the help is opened on top of my
    application frame.
    but - the second time It is opened - the only wat to
    recognize i sthe process is still active is to call
    exitValue (if it get an exception - process is still
    active) but - how can i make the frame on top of my
    application frame( the current active frame)Sorry I don't know the answer to that. What happens if you invoke it a second time... does it bring up a completely new frame?
    2.when the application is closed the help application
    does not "die" with the rest of the application.
    I will be happy to get some ideas of how can i
    control it.process.destroy()?

  • Problem writing to a file on a shared drive

    I am having problems with my application not writing to a file on a shared drive. Actually it works perfect on one computer, but not on any other computer. Any ideas on why this would not work. Here is my code below, I think this may be an issue with permissions on the shared drive but have played with those until I am sick of it and nothing works. Any help on getting it to write to a file on a shared drive would be great.
    report2 = new JButton("Provider Order Entry");
                        report2.addActionListener(new ActionListener() {
                             public void actionPerformed (ActionEvent e) {
                                  if (e.getSource() == report2) {
                                       try {
                                            File file = new File("z:\\Provider Order Entry Reports\\ACCESSFILE.RMD");
                                            FileReader checkAccess = new FileReader(file);
                                            BufferedReader checkAccessBuff = new BufferedReader(checkAccess);
                                            boolean eof = false;
                                            while (!eof) {
                                                 String line = checkAccessBuff.readLine();
                                                 if (line != null) {
                                                      eof = true;
                                                      checkAccess.close();
                                                      checkAccessBuff.close();
                                                      if (!poeSelectionWindow.isShowing()) {
                                                           poeSelectionWindow.setSize(575, 200);
                                                           poeSelectionWindow.setBackground(blue);
                                                           JFrame.setDefaultLookAndFeelDecorated(false);
                                                           poeSelectionWindow.setVisible(true);
                                                      else if (poeSelectionWindow.isShowing()) {
                                                           poeSelectionWindow.setVisible(false);
                                       catch (IOException error) {
                                            Component controllingFrame = null;
                                            JOptionPane.showMessageDialog(controllingFrame,
                                                       "YOU DO NOT HAVE ACCESS TO THIS OPTION" + "\n" +
                                                       "PLEASE CONTACT IRM SUPPORT TO REQUEST ACCESS ",
                                                       "ACCESS DENIED",
                                                       JOptionPane.ERROR_MESSAGE);
                                            try {
                                                 File errorFile = new File("Z:\\LOG\\LOGGER.log");
                                                 String username = System.getProperty("user.name");
                                                 InetAddress addr = InetAddress.getLocalHost();
                                                 Date date = new Date();
                                                 BufferedWriter bw = new BufferedWriter(new FileWriter(errorFile, true));
                                               bw.write("ACCESS ATTEMPTED ON: Provider Order Entry Report BY:" + username + " At Workstation/IP: "
                                                         + addr + " " + date);
                                               bw.newLine();
                                               bw.flush();
                                               bw.close();
                                            catch (IOException error1) {
                                                 System.out.println("Error-- " + error1.toString());
                                            catch (NullPointerException NPE) {
                                                 System.out.println("Error -- " + NPE.toString());                                                       
                                       catch (NullPointerException NPE) {
                                            System.out.println("Error -- " + NPE.toString());                                                       
                        });

    So how do I stop the
    NPE from occurring.By not dereferencing a null reference.
    Thingamabob xyz = doSomethingWhichMightReturnNull();
    if (xyz != null)
    // go ahead and use xyz here
    If you leave out the above "if" statement check, and just willy-nilly try to use xyz when it is null, you'll get the NPE.
    It is occurring on the file
    name. I have never been able to stop the file name
    from throwing a NPE.I don't know how that translates to some lines of your code.

  • Problem writing a segmented file to a a socket

    I have something like this:
    temp.out.writeObject("sot");
    temp.out.flush();
    temp.out.writeObject(fileName);
    temp.out.flush();
    for (int j=0;j<size;j=j+256){
                   byte[] temporary = new byte[256];
                   f.read(temporary,j,256);
                   System.out.println("J este " + j);
                   temp.out.writeObject(String.valueOf(j));
                   temp.out.flush();
                   temp.out.writeObject(temporary);
              temp.out.flush();
    temp.out.writeObject("-3");
         temp.out.flush();
    The problem is that it writes ok the "sot", it's writing ok the file name, and the first 256 bytes.
    After that the for stops at j=0. I don't get it ..

    sorry, I'm not really any good at reading other peoples code, but if it does what I think it does, here is how I do it
    int iHaveRead = 1;
              while(iHaveRead > 0){
              try {
    InBuffer = new byte[4096] ;
    iHaveRead = Sinput2.read(InBuffer, 0, 4096) ;
              } catch(IOException e) {
              System.out.println("Error on Input " + e) ;
              iHaveRead = -1 ;
              if(iHaveRead != -1){
              iToWrite = ProcData(iHaveRead) ;
              // write to Soutput
              try {
              Soutput.write(OutBuffer, 0, iToWrite) ;
    Soutput.flush() ;
    } catch(IOException e) {
              System.out.println("Error on Output " + e) ;
    iHaveRead = -1 ;
    where procData turns inbuffer to outbuffer and returns the size

  • Runtime.exec( )..can't find file

    Hi,
    i'm passing the path of a file to runtime.exec()
    but yet it's searching for the file in the working directory.
    exec is getting the following
    String [] command=new String[2];
    command[0]=new String(applicationToExecute);
    command[1]=new String(fileName);
    try {
    Process child = run.exec(command);
    }catch(){}.....
    applicationToExecute="mspaint.exe"
    fileName="c:\temp\time.jpg"
    However,
    it searches the working directory (directory which my program is running from) for "time.jpg".
    any ideas?
    help would be appreciated!
    finbarr
    it searchs

    Try to provide the full path to the command and use the forward slash instead of the backslash -- like this:
    String [] command=new String[2];
    command[0]=new String("C:/Program Files/Accessories/mspaint.exe);
    command[1]=new String("C:/temp/time.jpg");
    If that still doesn't work, then try this:
    String [] command=new String[3];
    command[0]=new String("command.com"); // or just cmd on XP
    command[1]=new String("C:/Program Files/Accessories/mspaint.exe);
    command[2]=new String("C:/temp/time.jpg");
    V.V.

  • Process/runtime.exec() problem

    i m trying to compile and run java files thru runtime.exec()...i m working on linux...when i compile a singe file it works all right....however when i compile multiple files using the same command only replacing "filename.java" by "*.java" its not working.
    error: cannot read: /home/pico/example/demo/*.java
    1 error
    any help will be appreciated

    I doubt, *.java will get replaced automatically with all your java-files. It's just treated as as file called "*.java", because resolving the wildcard is usually done by a shell which is not running when using Runtime.exec().
    You have to (re)solve it yourself.
    Hope this helped.

  • Runtime.exec() problem with Linux

    Hi All,
    I have a java program which I am using to launch java programs on all platforms.
    I am using the Runtime.exec() method to start the process in a separate JVM.
    But, I had a problem with the -classpath switch if the directories contained spaces. So I modified the java command which I am passing to the exec() method to something like:
    java -classpath \"./my dir with spaces\" com.harshal.MainThis I had to do because of the problem in windows. But, if I use double quotes in Linux (for the classpath switch in my exec() method), it won't work.
    Can anyone correct me so that I can use the Runtime.exec() method on all platforms to launch the java application even if the classpath directories contains spaces.
    Thank you very much.

    I was reading about the command line args on java's
    tutorial and I found a shocking news. Mac OS doesn't
    support command line args, That's news to me. Could you please elaborate ?
    More important is: I got it working. I figured out I had forgotten to try something before, or, to be more correct, I made an error when trying malcommc's envp suggestion: I used "classpath" as key, not "CLASSPATH", as it should have been.
    Ran a new test, got it working.
    Sample:
    Given a rootdir. Subdirectory "cp test" with a classfile (named "test") without package declaration. Running another class in another directory, using:
    String[] cmd = new String[]{
        "java", "test"
    String[] envp = new String[]{
        "CLASSPATH=rootdir:rootdir/cp test" // <-- without quotes.
    Runtime.getRuntime().exec(cmd, envp);It's been my wrong all the time. I didn't check hard enough. It simply had to work somehow (that's the kind of things that's easy to say afterwards :-)).

  • Problem writing object to file

    Hi everyone,
    I am creating an index by processing text files. No of files are 15000 and index is a B+ Tree. when all files processed and i tried to write it to the file it gives me these errors.
    15000 files processed.
    writing to disk...
    Exception in thread "main" java.lang.StackOverflowError
            at sun.misc.SoftCache.processQueue(SoftCache.java:153)
            at sun.misc.SoftCache.get(SoftCache.java:269)
            at java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:244)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1029)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1369)
            at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:380)
            at java.util.Vector.writeObject(Vector.java:1018)
            at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:585)
            at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:890)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1333)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1284)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1073)
            at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1245)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1069)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1369)
            at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:380)
            at java.util.Vector.writeObject(Vector.java:1018)
            at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:585)
            at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:890)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1333)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1284)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1073)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1369)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1341)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1284)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1073)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1369)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1341)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1284)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1073)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1369)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1341)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1284)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1073)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1369)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1341)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1284)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1073)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1369)
            at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1341)
            at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1284)
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1073)
            at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1369)
    ..........can anyone point out the mistake im doing?
    thanks

    the B+ Tree is balanced and is perfectly working without writing to the file. and i am using default writeObject() method of ObjectOutputStream.
      try {
                                FileOutputStream   f_out   = new   FileOutputStream ("tree.idx");
                                ObjectOutputStream obj_out = new   ObjectOutputStream (new BufferedOutputStream (f_out));   
         for (int x = 0, l = files.length; x < l; x++) {
              ProcessTree(files[x].toString());
                    System.out.println("Writing main index to the disk...");
                    obj_out.writeObject (tree); 
                    obj_out.flush();
                    obj_out.close();
                    } catch (Exception e)
          System.out.println (e.toString ());
          System.out.println("Error Writing to Disk!");
        }

  • Runtime exec problem to execute a C program

    Hi,
    I've spend lot of time trying to find a solution without success...
    My aim is to run a C program from a java application under linux. My C code is the following:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    main(int argc, char **argv){
    printf("hello world \n");
    Once compiled I run my java application wich run the binary through a runtime.exec().
    I followed the example given by
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    with the same input gobblers and threads.
    For some reason it doesn't work: nothing comes out...
    When I call "ls" instead of my binary it works perfectly!
    WHY??
    Any help would be greatly appreciated!

    Thanks for the reply.
    Yes it seems that JNI could be a solution, but it looks a bit complicated an maybe not so well adapted to my purpose.
    The executables I want to execute from my java application don't need any arguments.
    If JNI is really the only way I'll try to use it but is there any good reason why runtime exec doesn't work? It is supposed to execute any executable isn't it?
    cheers

  • Writing to external files

    Is there any documentation in addition to the standard SDK documet?
    I have to challenges:
    1. What LUA code do i use inside a typical "grid" to write seomthing to an external file ?
    2. How can I change settings for the stahdard image files. For example, I like to output the large files with a different JPEG compression than the thumbnails.

    Probably a newbie question...
    I tried the exampe from jarnoh above, but I get the error "Attempt to index local 'file' (a nil value).
    This is my code:
    local LrTasks = import 'LrTasks'
    local LrApplication = import 'LrApplication'
    local LrFunctionContext = import 'LrFunctionContext'
    local LrProgressScope = import 'LrProgressScope'
    local LrBinding = import "LrBinding"
    local LrView = import "LrView"
    local LrDialogs = import 'LrDialogs'
    local LrPathUtils = import 'LrPathUtils'
    local LrFileUtils = import 'LrFileUtils'
    local LrStringUtils = import 'LrStringUtils'
    local LrDate = import 'LrDate'
    local catalog = import "LrApplication".activeCatalog()
    function WriteExternalFile()
    local file = io.open("example.txt", "w")
    file:write("This is an test.")
    file:close()
    end
    WriteExternalFile()

  • Runtime exec() Problem, change working dir

    Hi!
    I have following problem:
    I want to call an executable from my home-directory under Linux this way:
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("/home/tom/prog/exec-command");
    Unfortunately I'm getting either exception "file not found" (but it's there) or no complain but no program run...
    perhaps something's wrong with the path-name?
    If I call the program in the directory with a shell it works fine.
    Would be very happy if anybody can give a hint!
    Thanks a lot,
    Manuel

    You are interested in the programs output? Does it write to stdout or stderr or both? In any case, my advice is to go multithreading and use one thread to wait for the program to exit, one to read stdout and one to read stderr. If you just use one thread for reading, the program might block. I normally use something like this:
      final int BUFFER = 2048;
      final Process p = Runtime.getRuntime().exec(args);
      //read standard out output of the external executable
      //in seperate thread to avoid I/O deadlocks
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getInputStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.out.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //read standard error output of the external executable
      //in seperate thread for symmetry
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getErrorStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.err.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //Wait for the external process to finish     
      int exitCode = p.waitFor();          
      if ( exitCode != 0 )
        throw new IOException("Executable stopped with error code "+exitCode); Cheers, HJK

  • Using Runtime exec() method to run java files and return runtime errors

    Hi
    I'm writing a java editor and I use
    Runtime.getRuntime().exec(command)
    to compile the java files. That works fine and I deal with the returned errors using the getErrorStream().
    My questions are:
    1. Can I use the same technique for returning runtime errors. In any posts I've read the process runs from begining to end, returning the errors after completion. How do I return the errors of the app as they happen interactively?
    2. If i cant use the exec and getErrorStream() methods then does anyone know how it is done?
    Thanks in advance for any help!

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

Maybe you are looking for