(Java) File redirection (both ways) within Runtime.exec?

前端 未结 1 793
抹茶落季
抹茶落季 2021-01-21 10:33

I want to execute this command:

/ceplinux_work3/myName/opt/myCompany/ourProduct/bin/EXECUTE_THIS -p cepamd64linux.myCompany.com:19021/ws1/project_name < /cepl         


        
相关标签:
1条回答
  • 2021-01-21 11:15

    Unless you are sending a file name to the standard input of the process, there is no distinction of whether the data came from a file or from any other data source.

    You need to write to the OutputStream given by Process.getOutputStream(). The data you write to it you can read in from a file using a FileInputStream.

    Putting that together might look something like this:

        Process proc = Runtime.getRuntime().exec("...");
    
        OutputStream standardInputOfChildProcess = proc.getOutputStream();
        InputStream dataFromFile = new FileInputStream("theFileWithTheData.dat");
    
        byte[] buff = new byte[1024];
        for ( int count = -1; (count = dataFromFile.read(buff)) != -1; ) {
            standardInputOfChildProcess.write(buff, 0, count);
        }
    

    I've left out a lot of details, this is just to get the gist of it. You'll want to safely close things, might want to consider buffering and you need to worry about the pitfalls of Runtime.exec().

    Edit

    Writing the output to a file is similar. Obtain a FileOutputStream pointing to the output file and write the data you read from Process.getInputStream() to that OutputStream. The major caveat here is that you must do this operation in a second thread, since accessing two blocking streams from the same thread will lead to deadlock (see the article above).

    0 讨论(0)
提交回复
热议问题