1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
import java.io.*;
import javax.comm.*;
import com.sun.comm.Win32Driver;
public class connection {
CommPortIdentifier portId;
static SerialPort port;
static InputStream in;
static BufferedReader br;
String donnees;
String s;
public connection() throws IOException, NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
//initialisation du driver
Win32Driver w32Driver= new Win32Driver();
w32Driver.initialize();
//récupération du port
try{
portId=CommPortIdentifier.getPortIdentifier("COM2");
//ouvrir le port
port=(SerialPort)portId.open("Mon_Appli", 20000);
//paramétrer le port
port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
port.setSerialPortParams
(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//gérer le flux d'entrée
in = port.getInputStream();
//lire les données
br = new BufferedReader(new InputStreamReader(in));
s = br.readLine();
while((donnees = br.readLine()) != null);
{
s += " " + donnees;
System.out.println(s);
}
//écrire les données
fichier("c:\\test.txt",s);
}finally
{
close();
}
}
//écrire les données dans un fichier
public void fichier(String monFichier, String mesDonnees)
{
FileWriter fw;
try {
fw = new FileWriter(monFichier, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(mesDonnees);
bw.newLine();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void close()
{
try {
in.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
port.close();
}
public static void main(String[] args) throws IOException, NoSuchPortException, PortInUseException, UnsupportedCommOperationException
{
new connection();
// new Interface();
}
} |
Partager