WebClub - Всероссийский Клуб Веб-разработчиков
WebClub.RU » Архив » Как я могу выполнять команду операционной системы из приложения Java? (Например "dir" или "ls" команду)

Как я могу выполнять команду операционной системы из приложения Java? (Например "dir" или "ls" команду)


Дата публикации: 17-03-2013

(От Marty Hall's Java страница)

import java.io.*;

/** A class that eases the pain of running external processes from
* applications.
* Lets you run a program three ways:
*

*
exec: Execute the command, returning immediately
* even if the commmand is still running. This would be appropriate
* for printing a file.
*
execWait: Execute the command, but don't return
* until the command finishes. This would be appropriate for
* sequential commands where the first depends on the second
* having finished (e.g. javac followed by
* java).
*
execPrint: Execute the command and print the output.
* This would be appropriate for the UNIX command ls.
*

* Note that, at least as of JDK 1.0, the path is not taken into
* account, and you must specify the full pathname to
* the command, and shell builtin commands will not work.
* For instance, on UNIX the above three examples might look like:
*

*
Exec.exec("/usr/ucb/lpr Some-File");
*
Exec.execWait("/usr/local/bin/javac Foo.java");
* Exec.execWait("/usr/local/bin/java Foo");
*
Exec.execPrint("/usr/bin/ls -al");
*

* Последнии версии кода:
*
* http://www.apl.jhu.edu/~hall/java/Exec.java.
* Послелнии версии документации:
*
* http://www.apl.jhu.edu/~hall/java/Exec.html.
*

* No warranty of any kind is provided (obviously :-).
* Permission is granted to use and/or modify the class file or sources
* for any purpose.
*


* 5/96 Marty Hall:
*


Страница Java Resource .

*
* @author Marty Hall (hall@apl.jhu.edu)
* @version 0.9 5/9/96
*/

public class Exec {
//-------------------------------------------------------------------

private static boolean verbose = true;

/** Determines if the Exec class should print which
* commands are being executed, and print error messages if
* a problem is found. Default is true.
*
* @param verboseFlag true: print messages. False: don't.
*/

public static void setVerbose(boolean verboseFlag) {
verbose = verboseFlag;
}

//-------------------------------------------------------------------
/** Starts a process to execute the command. Returns immediately,
* even if the new process is still running.
*
* @param command The full pathname of the command to be
* executed. No shell builtins or shell meta-chars allowed.
* @return false if a problem is known to occur, but since this
* returns immediately, problems aren't usually found.
* Returns true otherwise.
*/

public static boolean exec(String command) {
return(exec(command, false, false));
}

//-------------------------------------------------------------------
/** Starts a process to execute the command. Waits for the process to
* finish before returning.
*
* @param command The full pathname of the command to be
* executed. No shell builtins or shell meta-chars allowed.
* @return false if a problem is known to occur, either due to
* an exception or from the subprocess returning a non-zero value.
* Returns true otherwise.
*/

public static boolean execWait(String command) {
return(exec(command, false, true));
}

//-------------------------------------------------------------------
/** Starts a process to execute the command. Prints all output the
* command gives.
*
* @param command The full pathname of the command to be
* executed. No shell builtins or shell meta-chars allowed.
* @return false if a problem is known to occur, either due to
* an exception or from the subprocess returning a non-zero value.
* Returns true otherwise.
*/

public static boolean execPrint(String command) {
return(exec(command, true, false));
}

//-------------------------------------------------------------------

private static boolean exec(String command,
boolean printResults, boolean wait) {
if (verbose) {
printSeparator();
System.out.println("Executing '" + command + "'.");
}
try {
Process p = Runtime.getRuntime().exec(command);
if(printResults) {
DataInputStream commandResult =
new DataInputStream(new BufferedInputStream(p.getInputStream()));
String s = null;
try {
while ((s = commandResult.readLine()) != null)
System.out.println("Output: " + s);
if (p.exitValue() != 0) {
if (verbose)
printError(command + " -- p.exitValue() != 0");
return(false);
}
} catch (Exception e) {}
} else if (wait) {
try {
// Doesn't always wait. If the previous exec was a print-the-results
// version, then this will NOT wait unless there is a
// System.out.println call here! Odd...
System.out.println(" ");
int returnVal = p.waitFor();
if (returnVal != 0) {
if (verbose)
printError(command);
return(false);
}
} catch (Exception e) {
if (verbose)
printError(command, e);
return(false);
}
}
} catch (Exception e) {
if (verbose)
printError(command, e);
return(false);
}
return(true);
}

//-------------------------------------------------------------------

private static void printError(String command, Exception e) {
System.out.println("Error doing exec(" + command + "): " + e.getMessage());
System.out.println("Did you specify the full pathname?");
}

private static void printError(String command) {
System.out.println("Error executing '" + command + "'.");
}

//-------------------------------------------------------------------

private static void printSeparator() {
System.out.println
("====================================================================");
}

//-------------------------------------------------------------------
}
Предложение от Rich Morgan

Следующий код, который я нашел в телеконференции comp.lang.java. Этот код работает, но иногда он выдает на стандартный выход или на выход для сообщений об ошибках сообщение показывающее, что процесс был запущен и остановлен с кодом выхода. Блок try-catch должен включать exec.

Также Вы должны поместить полное имя пути в команду, которую Вы желаете использовать в exec. Это для меня не важно, поскольку execing /usr/bin/env показывает, что системная переменная PATH возвращает пути где могут быть найдены различные команды. По некоторым причинам выполнение метода exec не использует текущий PATH env переменной.

Также обратите внимание, что команды типа " ls /usr/* " не работают, если Вы не вызываете оболочку, чтобы выполнить команду: /usr/bin/sh -c ls /usr/* Проверенный код :

import java.io.*;

public class ls {
public static void main (String args[]) {
try {
Process p = Runtime.getRuntime().exec("/usr/bin/ls");
DataInputStream dis = new DataInputStream(
new BufferedInputStream(p.getInputStream()));

String s = null;
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e){
System.out.println("the detailed msg:" + e);
}
}
}

2.Как я могу загрузить и создать экземпляр под управлением программы?

Предложение от Lorenzo Patocchi

Основное псевдо приложение запускает метод, но не изменяет класса при его загрузке и использовании. Class1 и class2 - два класса, осуществляющие тот же самый интерфейс,


public class class1 implements genericclass{
public class1(){;}
public void method1(){
System.out.println("Hello, im class1 running method 1");
}
}
public class class2 implements genericclass{
public class2(){;}
public void method1(){
System.out.println("Hello, im class2 running method 1");
}
}
Имеется интерфейс ...


public interface genericclass{
public void method1();
}

Наконец это - динамический загрузчик класса:


public class dynamicload{
public static final String usage = "Usage: java dinamicload ";
public String className;
// WARNING: is important that this variable is declared
// as static !
public static genericclass genclass;

public static void main(String args[]) {
//Class c;
//Object obj;

if (args.length ==0){
System.out.println(usage);
return;
}
System.out.println("Class to Load: "+args[0]);

try{
// I just used a shortcut instantiating genclass
//c = Class.forName(args[0]);
//obj = c.newInstance();
//System.out.println("Instantiated " + obj.getClass().getName());
genclass = (genericclass) Class.forName(args[0]).newInstance();
genclass.method1();

}catch (InstantiationException instex){
System.out.println(instex);
}catch (IllegalAccessException illaccex){
System.out.println(illaccex);
}catch (ClassNotFoundException classnotfound){
System.out.println(classnotfound);
return;
}
}
}
ОБРАТИТЕ ВНИМАНИЕ: "class1" или "class2" НИКОГДА не появляются в динамическом классе. Теперь вы можете использовать этот код:


% java dynamic class1
Class to Load: class1
Hello, im class2 запускает method 1
% java dynamic class2
Class to Load: class2
Предложение от Cliff Berg

Имеется законченный пример, который создает простой загрузчик класса, и также проверяет из некоторых методов в классе Сlass. В одном файле, определите класс, который Вы желаете к динамически создать ...


import java.applet.*;

public class MyClass extends Applet
{
public MyClass()
{
}

public void init()
{
System.out.println("MyClass.init()");
}
}
Here is the code that instantiates and uses that class...
import java.awt.*;
import java.applet.*;
import java.io.*;
import java.util.*;

class ExtendedButton extends Button
{
ExtendedButton(String s)
{
super(s);
}

public boolean handleEvent(Event e)
{
System.out.println("ExtendedButton.handleEvent()");
return super.handleEvent(e);
}
}

class MyClassLoader extends ClassLoader
{
public Class loadClass(String name, boolean resolve)
// Define the class loader's behavior
throws
java.lang.ClassNotFoundException
{
// Here we could call the browser's class loader, or define
// our own...

// attempt to read the class from the current directory
try
{
FileInputStream fis = new FileInputStream(name + ".class");
File f = new File(name + ".class");
byte bytes[] = new byte[(int)(f.length())];
int n = fis.read(bytes);
Class c = defineClass(bytes, 0, bytes.length);
System.out.println("Read class, size=" + String.valueOf(bytes.length));
if (resolve) resolveClass(c);
return c;
}
catch (NullPointerException e)
{
}
catch (java.io.FileNotFoundException e)
{
}
catch (java.io.IOException e)
{
}
return null;
}
}

public class TestLoadClass extends Applet
{
public void init()
{
try {

ExtendedButton eb = new ExtendedButton("ExtendedButton");
add(eb);

//
// Try out some Class methods...
//

// Print the name of the ExtendedButton class
System.out.println("Instantiated " + eb.getClass().getName());

// Print the name of the ExtendedButton class
Class bc = Class.forName("ExtendedButton");
System.out.println("Obtained class descriptor for " + bc.getName());

// Get ExtendedButton's superclass
Class ebc = bc.getSuperclass();
System.out.println("ExtendedButton superclass: " + ebc.getName());


// Load the MyClass class
MyClassLoader cl = new MyClassLoader();
String className = "MyClass";
Class c = cl.loadClass(className, true);
if (c == null) throw new ClassNotFoundException();
System.out.println("Loaded " + c.getName());

// Instantiate a MyClass
Object o = c.newInstance();
System.out.println("Instantiated " + o.getClass().getName());
if (o instanceof MyClass)
System.out.println("o is ok");
else System.out.println("o not ok");
Object oc = new MyClass();
if (! (oc instanceof MyClass))
{
System.out.println("Error: class created as MyClass is "
+ oc.getClass().getName());
}
Applet ac = new MyClass();
if (! (ac instanceof MyClass))
{
System.out.println("Error: class created as MyClass is "
+ ac.getClass().getName());
}
MyClass mc = new MyClass();
if (! (mc instanceof MyClass))
{
System.out.println("Error: class created as MyClass is "
+ mc.getClass().getName());
}

//MyClass v = (MyClass)o; <- this fails in Beta 2, so use the
// next line instead
Applet ap = (Applet)o;
if (ap instanceof Applet)
System.out.println("ap is Applet"); // this executes
else System.out.println("ap not Applet");

ap.init();

}
catch (java.lang.ClassNotFoundException e)
{
System.out.println("Exception...ClassNotFoundException");
}
catch (java.lang.IllegalAccessException e)
{
System.out.println("Exception...IllegalAccessException");
}
catch (java.lang.InstantiationException e)
{
System.out.println("Exception...InstantiationException");
}

}

public void start() {}

public void stop() {}

public boolean handleEvent(Event e)
{
if (e.id == Event.WINDOW_DESTROY)
{
System.exit(0);
}
return false;
}

public static void main(String args[])
{
// Create a Frame
MainFrame f = new MainFrame("TestLoadClass");

// Instantiate the Applet
TestLoadClass applet = new TestLoadClass();

// Init and start the Applet
applet.init();
applet.start();

// Add the Applet to the Frame
f.add("West", applet);

// Resize and show the Frame
f.resize(300, 300);
f.show();
}
}


class MainFrame extends Frame
{
public MainFrame(String s) {
super(s);
}

// Handle close events by simply exiting
public boolean handleEvent(Event e) {
if (e.id == Event.WINDOW_DESTROY) {
System.exit(0);
}
return false;
}
}

3.Как я могу получить CLASSPATH переменную (и другие системные переменные)?

Предложение от Cliff Berg

Чтобы получить CLASSPATH переменную:

String classpath = System.getProperty("java.class.path");
Вы можете получить все системные переменные (и просмотреть те, которые являются доступными) используя:


Properties p = System.getProperties();
System.out.println(p);
Под win95, на моей системе получены этим способом вот такие переменные:


java.home=C:\JAVABETA2\JAVA\BIN\..,
awt.toolkit=sun.awt.win32.MToolkit,
java.version=1.0beta2,
file.separator=\,
line.separator=,
java.vendor=Sun Microsystems Inc.,
user.name=cliff,
os.arch=x86,
os.name=Windows 95,
java.vendor.url=http://www.sun.com/,
user.dir=C:\test,
java.class.path=.\;.\classes\;c:\JavaBeta2\java\classes\,
java.class.version=45.3,
os.version=4.0,
path.separator=;,
user.home=C:\JAVABETA2\JAVA\BIN\..


Вот и все!
Домен продается

Популярное

Не так давно в сети появился новый сервис, под названием Dead Man Zero. Этот сервис сделал...
Рынок социальных площадок уже давно стал стабильным. Несмотря на то, что время от времени...
Artisteer 4 – единственный в своем роде продукт, позволяющий автоматизировать работу над созданием...
Апрель 2024 (1)
Октябрь 2018 (14)
Февраль 2017 (3)
Январь 2017 (1)
Август 2016 (1)
Май 2016 (2)

Карта сайта: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41

Друзья сайта



Случайная цитата

Оноре де Бальзак:

"Тот, кто ищет миллионы, весьма редко их находит, но зато тот, кто не ищет, не находит их никогда."

Опрос

Какой браузер Вы используете?

Internet Explorer
Google Chrome
Mozilla Firefox
Netscape Navigator
Maxthon Browser
Opera
Mozilla Suite
SeaMonkey
K-Meleon
Safari
Amaya
Avant Browser
SlimBrowser
Другой...