在Java中获取进程的路径

时间:2016-05-11 16:11:40

标签: java unix process system-calls

我正在尝试将UNIX流stdoutstderr放入JavaFX文本区域。这是我创建的代码

import javafx.stage.Stage;
import javafx.scene.layout.VBox;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import java.io.InputStreamReader;
import java.io.BufferedReader;;
import java.io.IOException;
import java.io.File;
import java.util.Map;
public class SystemCallsGUI extends javafx.application.Application
{
    TextArea stdout;
    TextArea stderr;
    TextField commandField;

    @Override
    public void init()
    {
        stdout = new TextArea();
        stderr = new TextArea();
        commandField = new TextField();
    };
    @Override
    public void start(Stage primary)
    {
        VBox contents = new VBox();
        contents.getChildren().addAll(
            new Label("Enter Command"),
            commandField,
            new Label("Standard  Output"),
            stdout,
            new Label("Standard Error"),
            stderr);
        Scene s = new Scene(contents, 500, 600);
        commandField.setOnAction( e ->
        {
            doCommand(commandField.getText());
            commandField.setText("");
        });
        primary.setScene(s);
        primary.show();
    }
    public void doCommand(String command)
    {
        try
        {
            //Process p = Runtime.getRuntime().exec(command);
            String[] pieces = command.split("\\s");
            ProcessBuilder pb = new ProcessBuilder(pieces);
            Process p = pb.start();
            BufferedReader stdinReader = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(p.getErrorStream()));
            String line = "";
            StringBuffer bag = new StringBuffer();
            while( (line = stdinReader.readLine()) != null)
            {
                bag.append(line + "\n");
            }
            stdout.setText(stdout.getText() + bag);
            bag = new StringBuffer();
            while( (line = stderrReader.readLine()) != null)
            {
                bag.append(line + "\n");
            }
            stderr.setText(stderr.getText() + bag);
            Map<String, String> env = pb.environment();
            String wd = env.get("cwd");
            System.out.println(wd);
            //System.setProperty("user.dir", newDir);
        }
        catch(IOException ex)
        {
            System.out.println("IOException death");
        }
    }
}

我希望这个Java进程的cwd跟随底层shell的那个,所以如果我输入,例如cd,myhome目录就成了java的cwd处理。这是可能的还是Java中固有的安全违规?

0 个答案:

没有答案