📄 commconnecter.java
字号:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.comm.*;
public class CommConnecter implements Connecter {
private static final String libraryName="win32com";
private static final String driverName="com.sun.comm.Win32Driver";
private static CommDriver driver=null;
public SerialPort sPort;
public InputStream input;
public OutputStream output;
public BufferedReader reader;
public BufferedWriter writer;
protected static void intiDriver()throws Exception
{//初始化驱动程序
System.loadLibrary(libraryName);
driver=(CommDriver)Class.forName(driverName).newInstance();
}
public boolean Open(Object[] args) throws Exception {
//Args:BaudRate DataBits,StopBits,Parity
if(args.length<5)
throw new Exception("Open args=COMx 9600,8,1,0");
if(driver==null) intiDriver();
String portname=args[0].toString();
sPort=(SerialPort) driver.getCommPort(portname,
CommPortIdentifier.PORT_SERIAL) ;
//sPort==null 但以上语句不出现异常,说明有该串口,但被占用
if(sPort==null) throw new Exception("Port already opened");
// sPort.setSerialPortParams(sPort.getBaudRate(), sPort.getDataBits(), sPort.getStopBits(), sPort.getParity());
sPort.setSerialPortParams(Integer.parseInt(args[1].toString()),
Integer.parseInt(args[2].toString()),
Integer.parseInt(args[3].toString()),
Integer.parseInt(args[4].toString()));
output=sPort.getOutputStream();
writer=new BufferedWriter(new OutputStreamWriter( output));
input=sPort.getInputStream();
reader=new BufferedReader(new InputStreamReader(input));
return true;
}
public void Close() {
// TODO 自动生成方法存根
try {
reader.close();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
try {
writer.close();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
sPort.close();
}
public void setDTR(boolean b){ sPort.setDTR(b);}
public void setDTS(boolean b){ sPort.setRTS(b);}
public void SendDataAnsi(String cmd) throws Exception
{
//以ANSI码发送
byte[] bs=cmd.getBytes("GBK");
output.write(bs);
}
public String RecDataAnsi() throws Exception
{
byte[] bs=new byte[input.available()];
input.read(bs);
String rs=new String(bs);
return new String(rs.getBytes("GBK"),"GBK");
//接收流中的数据,以ANSI串形式返回
}
public Object getConObject() { return sPort;}
public InputStream getInputStream(){ return input;}
public OutputStream getOutputStream(){return output;}
public BufferedReader getReader() { return reader; }
public BufferedWriter getWriter() { return writer; }
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -