Tout d'abord, laissez-moi vous présenter mon programme. Mon application pure Java et utiliser comm jar pour le port COM. Je l'ai déjà ajoutéJava com port lire et écrire numéro
win32com.dll
-jre/bin
comm.jar
-jre/lib/ext
java.comm.properties
-jre/liv
Voici mon programme
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
public class PortReaderWriter
{
static Enumeration<?> ports;
static CommPortIdentifier portId;
static InputStream inputStream;
static OutputStream outputStream;
static SerialPort serialPort;
static String messageString = "abc";
public static void main(String[] args) throws Exception
{
try
{
ports = CommPortIdentifier.getPortIdentifiers();
while (ports.hasMoreElements())
{
portId = (CommPortIdentifier) ports.nextElement();
System.out.println("Port " + portId.getName());
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
if (portId.getName().equals("COM1"))
{
System.out.println("====================");
System.out.println("COM1 found");
serialPort = (SerialPort) portId.open("PortReaderWriter", 2000);
serialPort
.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
outputStream = serialPort.getOutputStream();
outputStream.write(messageString.getBytes());
System.out.println(messageString.getBytes() + " Successfully Sent!");
inputStream = serialPort.getInputStream();
byte[] readBuffer = new byte[2048];
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.println("numBytes " + numBytes);
}
System.out.print(new String(readBuffer));
outputStream = serialPort.getOutputStream();
outputStream.write(messageString.getBytes());
System.out.println(messageString.getBytes() + " Successfully Sent!");
System.out.println("====================");
}
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
La sortie est
Port COM3
Port COM1
====================
COM1 found
[[email protected] Successfully Sent!
====================
Port LPT1
Port LPT2
Mais mon résultat attendu est
COM1 found
[[email protected] Successfully Sent!
abc
====================
Port LPT1
Port LPT2
Dans le programme, je ne suis pas sûr « abc » est envoyé ou non, et dans la sortie je ne peux pas voir. S'il vous plaît aidez-moi est-il nécessaire d'ajouter ou de modifier. Merci d'avance!