- How To Compile and Run Java Program in Linux
- How to Compile Java Program
- How to Run Java Program
- How to Run Java from Command-line in Linux
- How to Run Java through Command-line
- Conclusion
- About the author
- Wardah Batool
- Работа с Java в командной строке
- От простого к .
- Один файл
- Отделяем бинарные файлы от исходников
- Используем пакеты
- Если в программе несколько файлов
- Если удивляет результат
- Хорошо бы протестировать
- Создадим библиотеку
- Надо узнать, что у библиотеки внутри
- Лучше снабдить библиотеку документацией
- Можно подписать jar-архив
- Использование библиотеки
- Собираем программу
- Первый способ
- Второй способ
- Третий способ
- Запуск исполняемого jar-файла
- Как быть с приложениями JavaEE
- How to run command-line or execute external application from Java
- How to run command-line or execute external application from Java
- Example
- Code Explanation:
- Output example
- Summary
- Related Posts
- Copy and Paste in Windows Command Prompt
- 96 Comments
How To Compile and Run Java Program in Linux
Today I’ll explain how to compile and run Java code on Linux environment.
Personally, I like Ubuntu, that’s why I’ll show you how to do it there.
First of all, you have to be sure that Java is installed on your machine.
Correct output is:
If it’s not installed you can do it easy:
Now change directory to your project source folder.
Inside of my project I have a class Car, that I wrote when I talked about the transient keyword in Java.
It looks like this:
How to Compile Java Program
To compile this class I call Linux Java compiler:
If everything was OK you should find a new file Car.class near Car.java.
Our class is compiled, the next step is to run compiled Java class on Ubuntu.
How to Run Java Program
In the previous section, I compiled Java code in Linux.
Now I’m going to show how to run Java program.
Just point Java to compiled class like this:
Note that you should run Java class from the source folder.
For example, if I change directory to project (one level upper than src folder).
and try to run the same class:
So you have to be sure that you’re running your Java code on Ubuntu from the source folder.
For compiling process it doesn’t matter.
As you can see it’s easy to compile and run Java on Linux.
Personally, I prefer Java programming on Linux instead of Windows.
I think Java developers should know at least basic Linux commands.
Источник
How to Run Java from Command-line in Linux
Java language is one of the most popular high-level object-oriented programming languages. It comes with a simple syntax and easily understandable for beginners, as it is very secure and economical to use. Java is the platform-independent software, and it also provides an auto garbage collection facility.
How to Run Java through Command-line
To run the java program in Linux, we need to verify if Java Development Kit (JDK) is available in the system and its version.
To confirm it, type the following command:
(Javac command-line tool is used for the compilation of java programs)
The Javac command tool is not available in my system. We have multiple commands to download it, as mentioned in the above image.
Let’s go with the default-jdk command to get it:
To verify the installation of javac, type:
Now, write a Java program in the text file and save it with .java extension.
Suppose I created a file named “testing.java” and write a simple program in it:
(Keep in mind that your class name should be the same as the file name)
Compile the testing.java file on the terminal using the javac command:
Now, execute the Java program by calling its class name in the terminal:
Conclusion
Java is the high-level language of the modern era supported by the Java Development Kit (JDK). JDK is a package that helps to run java and is used for the development of software packages.
Java language comes with a simple syntax that is easy to get for beginners, and it is one of the most usable object-oriented programming languages.
We have seen in this article that how to install and run Java applications on the terminal.
About the author
Wardah Batool
I am a Software Engineer Graduate and Self Motivated Linux writer. I also love to read latest Linux books. Moreover, in my free time, i love to read books on Personal development.
Источник
Работа с Java в командной строке
От простого к .
Каждая программа обычно содержится в отдельном каталоге. Я придерживаюсь правила создавать в этом каталоге по крайней мере две папки: src и bin. В первой содержатся исходные коды, во второй — результат компиляции. В данных папках будет структура каталогов, зависящая от пакетов.
Один файл
Можно сделать и без лишних папок.
Берем сам файл HelloWorld.java.
Переходим в каталог, где лежит данный файл, и выполняем команды.
В данной папке появится файл HelloWorld.class. Значит программа скомпилирована. Чтобы запустить
Отделяем бинарные файлы от исходников
Теперь сделаем тоже самое, но с каталогами. Создадим каталог HelloWorld и в нем две папки src и bin.
Компилируем
Здесь мы указали, что бинарные файлы будут сохраняться в отдельную папку bin и не путаться с исходниками.
Используем пакеты
А то, вдруг, программа перестанет быть просто HelloWorld-ом. Пакетам лучше давать понятное и уникальное имя. Это позволит добавить данную программу в другой проект без конфликта имен. Прочитав некоторые статьи, можно подумать, что для имени пакета обязательно нужен домен. Это не так. Домены — это удобный способ добиться уникальности. Если своего домена нет, воспользуйтесь аккаунтом на сайте (например, ru.habrahabr.mylogin). Он будет уникальным. Учтите, что имена пакетов должны быть в нижнем регистре. И избегайте использования спецсимволов. Проблемы возникают из-за разных платформ и файловых систем.
Поместим наш класс в пакет с именем com.qwertovsky.helloworld. Для этого добавим в начало файла строчку
В каталоге src создадим дополнительные каталоги, чтобы путь к файлу выглядел так: src/com/qwertovsky/helloworld/HelloWorld.java.
Компилируем
В каталоге bin автоматически создастся структура каталогов как и в src.
Если в программе несколько файлов
HelloWorld.java
Calculator.java
Adder.java
Ошибка возникла из-за того, что для компиляции нужны файлы с исходными кодами классов, которые используются (класс Calculator). Надо указать компилятору каталог с файлами с помощью ключа -sourcepath.
Компилируем
Если удивляет результат
Есть возможность запустить отладчик. Для этого существует jdb.
Сначала компилируем с ключом -g, чтобы у отладчика была информация.
Отладчик запускает свой внутренний терминал для ввода команд. Справку по последним можно вывести с помощью команды help.
Указываем точку прерывания на 9 строке в классе Calculator
Запускаем на выполнение.
Чтобы соориентироваться можно вывести кусок исходного кода, где в данный момент находится курссор.
Узнаем, что из себя представляет переменная а.
Выполним код в текущей строке и увидим, что sum стала равняться 2.
Поднимемся из класса Adder в вызвавший его класс Calculator.
Удаляем точку прерывания
Можно избежать захода в методы, используя команду next.
Проверяем значение выражения и завершаем выполнение.
Хорошо бы протестировать
Запускаем. В качестве разделителя нескольких путей в classpath в Windows используется ‘;’, в Linux — ‘:’. В консоли Cygwin не работают оба разделителя. Возможно, должен работать ‘;’, но он воспринимается как разделитель команд.
Создадим библиотеку
Класс Calculator оказался полезным и может быть использован во многих проектах. Перенесем всё, что касается класса Calculator в отдельный проект.
Измените также назавания пакетов в исходных текстах. В HelloWorld.java нужно будет добавить строку
Делаем архив jar
С помощью ключа -C мы запустили программу в каталоге bin.
Надо узнать, что у библиотеки внутри
Можно распаковать архив zip-распаковщиком и посмотреть, какие классы есть в библиотеке.
Информацию о любом классе можно получить с помощью дизассемблера javap.
Из результата видно, что класс содержит кроме пустого конструктора, ещё один метод sum, внутри которого в цикле вызывается метод add класса Adder. По завершении метода sum, вызывается Adder.getSum().
Без ключа -c программа выдаст только список переменных и методов (если использовать -private, то всех).
Лучше снабдить библиотеку документацией
Изменим для этого класс калькулятора.
Документацию можно создать следующей командой. При ошибке программа выдаст список возможных опций.
В результате получиться следующее
Можно подписать jar-архив
Если требуется подписать свою библиотеку цифровой подписью, на помощь придут keytool и jarsigner.
Генерируем подпись.
Генерируем Certificate Signing Request (CSR)
Содержимое полученного файла отправляем в центр сертификации. От центра сертификации получаем сертификат. Сохраняем его в файле (например, qwertokey.cer) и импортируем в хранилище
Файл qwertokey.cer отправляем всем, кто хочет проверить архив. Проверяется он так
Использование библиотеки
Есть программа HelloWorld, которая использует библиотечный класс Calculator. Чтобы скомпилировать и запустить программу, нужно присоединить библиотеку.
Компилируем
Собираем программу
Это можно сделать по-разному.
Первый способ
Здесь есть тонкости.
В строке
не должно быть пробелов в конце.
Вторая тонкость описана в [3]: в этой же строке должен стоять перенос на следующую строку. Это если манифест помещается в архив сторонним архиватором.
Программа jar не включит в манифест последнюю строку из манифеста, если в конце не стоит перенос строки.
Ещё момент: в манифесте не должно быть пустых строк между строками. Будет выдана ошибка «java.io.IOException: invalid manifest format».
При использовании команды echo надо следить только за пробелом в конце строки с main-class.
Второй способ
В данном способе избегаем ошибки с пробелом в main-class.
Третий способ
Включили код нужной библиотеки в исполняемый файл.
Запуск исполняемого jar-файла
Файл calculator.jar исполняемым не является. А вот helloworld.jar можно запустить.
Если архив был создан первыми двумя способами, то рядом с ним в одном каталоге должна находится папка lib с файлом calculator.jar. Такие ограничения из-за того, что в манифесте в class-path указан путь относительно исполняемого файла.
При использовании третьего способа нужные библиотеки включаются в исполняемый файл. Держать рядом нужные библиотеки не требуется. Запускается аналогично.
Как быть с приложениями JavaEE
Аналогично. Только библиотеки для компиляции нужно брать у сервера приложений, который используется. Если я использую JBoss, то для компиляции сервлета мне нужно будет выполнить примерно следующее
Структура архива JavaEE-приложения должна соответствовать определенному формату. Например
Способы запуска приложения на самом сервере с помощью командной строки для каждого сервера различны.
Надеюсь, данная статья станет для кого-нибудь шпаргалкой для работы с Java в командной строке. Данные навыки помогут понять содержание и смысл Ant-скриптов и ответить на собеседовании на более каверзные вопросы, чем «Какая IDE Вам больше нравится?».
Источник
How to run command-line or execute external application from Java
How to run command-line or execute external application from Java
Have you ever confront a situation that you need to execute external programs while developing a Java application? For instance, you are developing a Java application and need to execute external application(another executable program) in the middle of the program or you may need to execute some commands such as listing directory command: dir (in windows) or ls (in Unix) while developing the program. The following will show you how to execute the external program from Java application.
Example
Note: The example will use NetBeans as IDE.
Let see the example Java source code below:
The above Java’s code will try to execute the external program (helloworld.exe) and show output in console as exit code of the external program.
The sample external program, Helloworld.exe (Visual Basic)
Code Explanation:
Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(«c:\\helloworld.exe»);
Create Runtime Object and attach to system process. In this example, execute the helloworld.exe.
If you want to execute some commands, just modify the string in the rt.exec(“….�?) to command that you want.
For instance, in the comment line; //Process pr = rt.exec(“cmd /c dir”);
Note: that you need to enter “cmd /c …�? before type any command in Windows.
int exitVal = pr.waitFor(); System.out.println(«Exited with error code «+exitVal);
Method waitFor() will make the current thread to wait until the external program finish and return the exit value to the waited thread.
Output example
Process pr = rt.exec(“c:\\helloworld.exe”);
Process pr = rt.exec(“cmd /c dir”);
Summary
This is a simple code to execute external applications. If you want to call functions from other program (ex. C++, Visual Basic DLL), you need to use JNI (Java Native Interface) which you can find a nice tutorial at codeproject.com.
If you need more information, below are some sites that talk about executing external code.
For Java users
- Execute an external program – Real’s Java How-to.
http://www.rgagnon.com/javadetails/java-0014.html - When Runtime.exec() won’t – Java World.
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html - Trouble with Runtime.getRuntime().exec(cmd) on Linux – Java.
http://www.thescripts.com/forum/thread16788.html - Runtime.getRuntime().exec (Linux / UNIX forum at JavaRanch).
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=13&t=001755 - Java’s Runtime.exec() and External Applications.
http://www.ensta.fr/
For C++ users
- How can I start a process?
http://www.codeguru.com/forum/showthread.php?t=302501 - Executing programs with C(Linux).
http://www.gidforums.com/t-3369.html
Related Posts
Copy and Paste in Windows Command Prompt
96 Comments
Great 🙂 Helped me a lot 🙂 Thanks 🙂
How about executing a command from UNIX? i.e.
cat test.txt | mailx [email protected]
What does my string look like?
As from your string, you do not need output line so you can comment out the while loop that print output and if I reference from the source code in my post, the code will look like
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
/*while((line=input.readLine()) != null) <
System.out.println(line);
>*/
int exitVal = pr.waitFor();
System.out.println(“Exited with error code” +exitVal);
> catch(Exception e) <
System.out.println(e.toString());
e.printStackTrace();
>
If you want more information, try to follows the links that I’ve just added at the bottom of the post.
I’m a java beginner,I have an error that on running java using editplus&jdk1.6.0_02 version cannot disply output.What I can do
Also please give me goodlink in java for developing software
How add a data into database using java
To Mubarak,
1. What is your error message?
2. If you are a beginner, I recommends text book “Core Java 2, Volume I–Fundamentals”. You can find one at amazon.com
3. That depends on which database you are using.
Next time, please don’t separate comment.
Good article. Can you give suggestions for remote login using java programs.
Yo!
Wasjust serfing on net and found this site…want to say thanks. Great site and content!
This helped me a lot…
Nice article. Helped me a lot. Thx!
I’m kind of new to the topic, and would really appreciate if you did a comment on how to use the outputstream for a process.
My Java class will execute the linux CAT command to join files as:
Process p = Runtime.getRuntime().exec(“cat a.txt b.txt > e.txt”);
I always receive error:
cat: >: No such file or directory
Note: a.txt and b.txt is existed.
Could anyone help me?
I would Just like to say that this has been gloriously helpful to me today, and that I very much appreciate you for helping out the general community.
Very helpful linglom, thanks.
Here is an example that sends an email, where the body of the mail is in a text file.
static private void remote_call_11 () <
System.out.println(“\nstatic private void remote_call_11 ()” );
try <
Runtime rt = Runtime.getRuntime();
String subject=” TestSubject11″;
String pipeFile=”/tmp/test2.out | “;
String email=”[email protected]”;
String cmdline=”cat ” + pipeFile + ” mail -s ” + subject + ” “+email;
String[] cmd = <“/bin/bash”,”-c”,cmdline>;
Process pr = rt.exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
int exitVal = pr.waitFor();
System.out.println(“Exited with error code ” +exitVal);
> catch(Exception e) <
System.out.println(e.toString());
e.printStackTrace();
>
> // remote_call_11
Hello, Thomas.
Thanks for your sharing.
Very Helpful! Thanks.
do you know a way to interact with cmd without “/c”.
Im asking this because im trying to interact with gdb debugger, but the /c command its not available so i cant pass my arguments correctly.
“/c” is a parameter of cmd command. Why it doesn’t available?
So what exactly do you want to do with gdb debugger?
thanks for posting….i want to debug a C file from a java application.
But when I interact with gdb like this from java:
i cant because everything passed after gdb is passed like arguments so i get an error, and i cant use the “/c” or “&&” comand i would use with cmd to pass multiple commands.
Basically i want to debug a C file from java.
Do you know any tip?
Is it possible to put your gdb parameters after /c command?
Like this, pr = rt.exec(“cmd /c gdb …your gdb parameter goes here…”);
If it doesn’t work, what about batch (.bat) file. Write the gdb command in the batch file. I have provide some links in the summary section. Some of them has example about batch file.
thanks for the tip linglom, i wrote the commands in a .txt file and used the -x command, like this:
BUT I GOT AN ISSUE….WHEN I EXECUTE THE JAVA PROGRAM, A CONSOLE WINDOW APPEARS VERY QUICKLY, JUST LIKE THE ONE THAT APPEARS WHEN YOU USE GDB FROM COMMAND LINE, IT CLOSES VERY FAST BUT IN THE END IT APPEARS, IS THERE A WAY TO OBVIATE THIS EVENT.
You can set the batch file to pause until you press any key by add ‘pause’ to the end of a batch file.
For example, “test.bat”
thanks linglom, you have been very helpful, another question. I want to interact with cmd from java, an example: supose you have a program in C with a “scanf();” line and i want to execute that program and interact with it from inside my java program.
I do this:
String cmd = â€cmd /c myCprogram.exe”;
p = Runtime.getRuntime().exec(cmd);
but it wont work because it will stay blocked expecting that i enter a value to the “scanf();”. How can i solve this.
PS. A batch file is too complicated because i dont always now how many “scanf();” will be in the C program.
linglom, your suggestions to John have been very helpful. I’ve tried applying your script recommendations but am having a small issue.
I have a series of SQL commands that are performed on a database table. This string is called within a batch file.
I would like to execute it within java. This is what I have written using your previous suggestions. String cmd[] = <“cmd”,”mysql -h host -u user -p pass clientexport linglom January 11, 2009
To John,
Your problem seems to be complicated. If you have to interact with external application many times in different way, it may not good to write application to interact with it. I think it’s hard to debug and maintain your application. I have better way. Try AutoIt, it is a tool to create script that interact with Windows GUI. It is easy to use. Let’s see it yourself – AutoIt v3.
To Harris,
I think the best way is to try to run the code outside the batch file first to test if the command is correctly or not.
This is a very good topic,thanks linglom.
I was trying to copy files from one folder to another folder and it worked well.
But when i tried to execute a DOS del from Java, the program was hanged. I am sure that was because DOS command promt will ask for a confirmation before it does the delete :
Are you sure (Y/N):
Can you guys help me out? Thanks
Regards
I’ve solved the problem by putting /Q (Quiet mode, do not ask if ok to delete on global wildcard) parameter for del command.
Process pr = rt.exec(“cmd /c del /Q C:\\Laser\\*.*”);
Hi, Kevin Do
Thanks for your sharing.
I am able to run DOS command from JAVA in following way
String fullPath = “cmd /c start D:\\tool\\citi\\bin\\properties\\build os “;
Runtime rt= Runtime.getRuntime();
try <
Process p=rt.exec(fullPath.toString());
>catch (Exception exception) <
>
But now i want to close the command prompt window . How to do this. Please help me out ..
Hi, Nikhil
Try to modify the command by add “” after start command as the example below,
From:
cmd /c start “C:\Program Files\WinRAR\WinRAR.exe”
To:
cmd /c start “” “C:\Program Files\WinRAR\WinRAR.exe”
It didnt worked.
is there any other way out to close the command propmp window .
Following is the command which am firing to open the command prompt
String fullPath = “cmd /c start D:\\tool\\citi\\bin\\properties\\build.bat /c ”
Runtime rt= Runtime.getRuntime();
Process p=rt.exec(fullPath.toString());
What if you remove the text “cmd /c start”?
String fullPath = “D:\\tool\\citi\\bin\\properties\\build.bat /c”
i have to run this command in windows…
i have a folder containing two files named “a” and “b”
the command is
t2mf -r a b
how do i do that pls tell
continued….
by cmd i m doing like this …
i m going inside that folder by cd commmand …
and typing this command
t2mf -r a b
where a is input file already existing and b is output file generated..
Hi, Amit
Try to modify the code in the post.
“cmd /c t2mf -r a b”
thanks a lot for this article
i am planning to develop a playlist app for mplayer in linux using this techinque
Do you have articles on Qt development.
If yes , please send link to : [email protected]
Hi all, thanks for your advice; these comments have been very helpful to me. I am trying to get Java to run the following Mac OS X terminal command:
That command successfully runs from the terminal to turn the .tex file into a .pdf.
I have used your strategies with
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
so that Java will for example successfully execute
but when I try to use pdflatex, I get the following error:
java.io.IOException: pdflatex: not found
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.(UNIXProcess.java:52)
at java.lang.ProcessImpl.start(ProcessImpl.java:91)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
at java.lang.Runtime.exec(Runtime.java:591)
at java.lang.Runtime.exec(Runtime.java:464)
Clearly, the pdflatex command is not supported by the runtime exec bit, but since both commands work as expected from the Terminal, I was wondering if you knew any way to instruct the Terminal directly to execute the command.
Hi everybody,
I am executing a XOG utility like this on commmand line…
C:/MyWorks/xog -propertyfile test.properties
I am getting this output
—————————————-
Using https
Configuring context for TLS
———————————————————–
Clarity XML Open Gateway ( version: 12.0.1.5063 )
———————————————————–
Login Succeeded
Request Document: rsm_resources_read_xog1.xml
Writing output to Outputrsm_ShipraResource_read.xml
Request Succeeded
Logout Succeeded
———————————————–
Then I get the below exception …
java.io.IOException: CreateProcess: D:\MyWorks\xog -propertyfile D:/MyWorks/test.properties error=193
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
at java.lang.Runtime.exec(Runtime.java:591)
at java.lang.Runtime.exec(Runtime.java:464)
at com.Test.main(Test.java:49)
I have tried with giving the extension to ‘xog’ command but it doesn’t help. I also have tried to run the resultant process string on the command line i.e.
D:\MyWorks\xog -propertyfile D:/myworks/test.properties
I get the following output
——————————-
Using https
Configuring context for TLS
———————————————————–
Clarity XML Open Gateway ( version: 12.0.1.5063 )
———————————————————–
No valid input files specified
Usage: xog
Arguments:
-username
-password
-servername
-portnumber
-input input
-output output
-propertyfile (used in place of any or all parameters above)
——————————————————
I think there is some problem with properties file. Process is not able to read that file while both files are same.
Can anybody help me?
Hello Linglom and All
Could you please help me about a java code which will run in windows for executing some shell script in Some Sun Machine?
Usually I telnet , input user name and password and run a script. I need to do it from my windows java application.
Hi, Ashikur Rahman
If you use telnet command, it will need to interact with a user. So I suggest you create a script which do your task first and then call the script from your java application later.
To create a script, you can try autoit which is a free software helps you to create scripts to automate tasks on Windows. See, AutoIt
I tried to execute this
Process p = Runtime.getRuntime().exec(“cat ABCD.* > filejadi2.txt”);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
it is run but there isn’t result file (filejadi2.txt)
help me please.
thanks.
Hi, Sifa
Try with a basic command such as listing directory to see if there is any result or not.
Thanks for the nice article. I also found it extremely helpful!
This thread is very useful, but it misses one important issue that I was not able to find a solution for.
Does anybody know which default username is used by JVM when it runs the external shell scripts via Runtime.getRuntime().exec ?
Is there a way to set this username somewhere?
I’m trying to run an external script containing privileged system commands using sudo, but I have no idea which user I should give the privilege to…
Many thanks for your help.
Very informative. Nice article.
Hi, tokared
I’m not sure but I think it’s the same user as you run the java application.
If it is on Windows and you want to run the command as a specified user, I will use Runas command.
Hi
This works fine for jobs that finish and give it’s feedback immidiately and then closes. But how shall I do it for jobs that run “for a while”, for example a “tar -tvf” to tape drive ?
Excellent and very helpful article, Linglom. Thank you for posting it. For me the comments may be even more helpful…
I have a similar problem as Kevin (above) but some of the os-agnostic applications I am launcing do not have a /q or “quite mode”. Is there any way to create a 2-way interactive process or thread?
I have the following:
String line=»»;
BufferedReader br;
br = new BufferedReader(new InputStreamReader(System.in));
StringBuffer s2 = new StringBuffer();
Runtime oShell = Runtime.getRuntime();
String oSysName = System.getProperty(«os.name» );
if(oSysName.toUpperCase().startsWith(«WIN»)) <
// We need to make this OS Agnostic
line = «cmd.exe /c «+getPath(sCommand)+».cmd»; // Shell Out to Win32
> else < line = "/bin/sh -c "+getPath(sCommand); >// Shell to UNIX, Linux or MAC
String args[] = line.split(«[ \t]+»); // tokenize the commandLine into an array for exec()
System.out.println(«\n SHELL> Type any additional parameters, end with ^D (UNIX) or ^Z (Win32) + [Enter] \n\n»);
do <
line = br.readLine();
if (line != null) < args = addArrayNode (args, line); >
> while (line != null);
System.out.print(» SHELL> Executing Command, Please Wait. «);
System.out.print(«\n\n The Following String is being sent to «+oSysName+ » for processing:\n\t»+Arrays.toString(args));
Process oProc = oShell.exec(args); //Process Launcher
// create reader to get errors as a character stream from the child process.
final BufferedReader errorHandler =
new BufferedReader(new InputStreamReader(oProc.getErrorStream()));
// create reader to get standard output as a character stream from child process.
final BufferedReader outputHandler =
new BufferedReader(new InputStreamReader(oProc.getInputStream()));
Then I launch threads to capture and display the output. such as:
//Get and display the standard output produced by the child process. (for non-ERRORs)
Thread stdoutThread = new Thread() <
public void run() <
try < int l; String line;
for(l = 0; (line = outputHandler.readLine()) != null; ) <
if (line.length() > 0) < l++; outputLines.addElement(line); >
System.out.println(line);
>
if (l >0) System.out.print(«\n\nRead » + l + » lines (above) from stdout.»);
outputHandler.close();
> catch (IOException ie) < System.out.println("SHELL>IO exception on stdout: » + ie); >
>
>;//end-sddoutThread-def
I’m having a hard time getting my head around the (interactive scenario’s) thread handler. How do I know if it needs a response? Which thread should I watch? Both? Maybe use: getOutputStream .
not sure if my code snippits will be formatted properly, but any help would be greatly appreciated..
Источник