我的程序可以使用 inputStream.toString();
运行,但如您所知,这不是将 inputStream
转换为 String
的好方法。因此,当我尝试正确转换时,它会挂起。
我的方法是:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
if(initialized && connected){
try{
sms.findOperator();
jTextArea2.append(sms.logString);
sms.logString = "";
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Failed to find operator!", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
else JOptionPane.showMessageDialog(null, "Cannot connect to the port specified!", "ERROR", JOptionPane.ERROR_MESSAGE);
// TODO add your handling code here:
}
这是 findOperator()
方法:
public void findOperator(){
send("AT+COPS?\r\n");
}
这是send()
方法:
public void send(String cmd) {
try {
//Thread.sleep(200);
outputStream.flush();
outputStream.write(cmd.getBytes());
inputStream = serialPort.getInputStream();
//System.out.println(" Input Stream... " + inputStream.toString());
Thread.sleep(300);
logString += inputStreamtoString(inputStream);
}
catch(Exception e){
e.printStackTrace();
}
finally{
//logString += inputStream.toString()+ '\n';
// if(infoType == "msg") return "Input Stream... " + inputStream.toString()+ '\n';
// else return inputStream.toString();
//return logString;
//logString += inputStreamtoString(inputStream);
}
}
这是 inputStreamtoString()
方法:
public String inputStreamtoString(InputStream is) throws IOException{
// try {
// return new java.util.Scanner(is).useDelimiter("\\A").next();
// } catch (java.util.NoSuchElementException e) {
// return "";
// }
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
如果我不使用 inputStreamtoString()
方法并使用 inputStream.toString()
我的程序运行良好,但我没有得到正确的字符串。有什么建议吗?
提前致谢...
更新:我的调制解调器使用带有 GSM SIM 卡的端口 COM3
。我得到一个包含巨大空间的字符串,例如:
+COPS: <...500 spaces...> 0,0,"Banglalink"
所以我讨厌那个空间。我需要一个字符串:+COPS: 0,0,"Banglalink"
最佳答案
您正在尝试从连接到串行端口的流中彻底读取(即直到读取所有数据)。如果端口上没有可用数据(等待数据到来),这将挂起。即使有数据,也会出现无限循环。
更新: 您可以尝试这样的方法(改编自列出的代码 here ):
byte[] readBuffer = new byte[200];
try {
while (is.available() > 0) {
int numBytes = is.read(readBuffer);
sb.append(new String(readBuffer, "US-ASCII"));
}
} catch (IOException e) {
// handle exception
}
更新:更改字符串创建以使用指定的字符集(而不是系统默认值)
关于java - 将 InputString 转换为 String 就好像程序没有挂起一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10123315/