【发布时间】:2013-12-24 22:44:39
【问题描述】:
我正在尝试使用 shell 和 java 的组合来读取和写入串行端口。目标是能够使用 PrintWriter 和 BufferedReader 从连接到串行端口的设备发送和接收命令。我知道这可以通过不同的方式完成(不使用 shell),但这不是我想要的。我希望能够使用 shell 和 java 来做到这一点。
这是我的代码:
static String port = "/dev/tty.usbmodem411";
static int baudRate = 9600;
private static String command = "screen " + port + " " + baudRate;
public static void main(String[] args) throws Exception {
System.out.println("Command is " + command);
Process p = Runtime.getRuntime().exec(command);
//p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = reader.readLine();
while(true)
{
if (line != null) {
System.out.println(line);
}
line = reader.readLine();
}
}
使用此代码,我专门尝试从串行端口读取。我正在使用 java 运行 shell 命令来访问串行端口,然后读取命令的输出。
但是,当我运行此代码时,我总是收到一条消息“必须连接到终端”。我也尝试将command = "screen " + port + " " + baudRate; 更改为command = "screen -dm" + port + " " + baudRate;,但我没有得到任何输出。我咨询过几个类似的问题,Executing screen command from Java和How to open a command terminal in Linux?
但我仍然无法弄清楚我应该怎么做才能解决这个问题。我有一种感觉,它一定很简单,但经过数小时的研究,我无法弄清楚该怎么做。
【问题讨论】:
-
有时我们无法得到我们想要的。有时我们可以...我会使用 kermit 表示 this。
-
我知道这不是最好的方法,但如果可能的话,我想解决这个错误。
-
命令不应该是一个字符串数组,每个参数是一个不同的字符串...
-
我很确定这没关系,但我会继续检查。
-
更新:将命令更改为字符串数组似乎对代码没有影响。我得到了完全相同的结果。
标签: java shell terminal serial-port arduino