我正在尝试在由Java生成的shell中运行BASH脚本然后 使用JTextArea显示所述BASH脚本的结果。
import java.io.IOException;
public class Bobsors {
public static Mainframe frame;
public static void main(String[] args) {
frame = new Mainframe();
frame.start();
run();
}
public static void run() {
String[] cmd = new String[]{"/bin/sh", "PATH=~/Desktop/bobsors.sh"};
try {
Process process = Runtime.getRuntime().exec(cmd);
frame.setLog(process);
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
@SuppressWarnings("serial")
public class Mainframe extends JFrame {
private JPanel contentPane;
public static Mainframe frame;
public static JTextArea log = new JTextArea();
/**
* Launch the application.
*/
public void start() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Mainframe();
frame.setVisible(true);
frame.setTitle("Bobsors Java Application.");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void setLog(Process process) {
log.setText(process.toString());
}
/**
* Create the frame.
*/
public Mainframe() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Shell Log", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBounds(7, 50, 434, 217);
contentPane.add(panel);
panel.setLayout(null);
log.setBounds(5, 17, 424, 210);
log.setEditable(false);
panel.add(log);
JLabel lblBobsors = new JLabel("Bobsors");
lblBobsors.setBounds(12, 12, 70, 15);
contentPane.add(lblBobsors);
JLabel lblWorksOnLinux = new JLabel("Works on Linux only");
lblWorksOnLinux.setBounds(12, 26, 203, 15);
contentPane.add(lblWorksOnLinux);
}
}
当运行时,唯一显示的是这个 “java.lang.UNIXProcess@509d5bae” 有谁知道如何正确地做到这一点?
答案 0 :(得分:3)
Process
不会覆盖从toString()
继承的默认Object
方法,因此会显示该值。
相反,您可以使用getInputStream()
,它会返回一个InputStream
对象,您可以将其转换为如下字符串:Read/convert an InputStream to a String。
同样不要忘记EDT
(事件派发线程)上的任务必须快速完成;如果他们不这样做,未处理的事件将备份,用户界面将无法响应,因此请确保使用其他线程。
答案 1 :(得分:0)
您可以使用InputStream
和BufferedReader
来阅读输出,如下所示
InputStream input = process.getInputStream();
BufferedReader result = new BufferedReader(new InputStreamReader(input));
转换为字符串
StringBuilder builder = new StringBuilder();
String line="";
while((line=result.readLine()) != null){
builder.append(line + "\n");
}
请添加try
& catch
恰当。