Newsgroup: it.comp.java
Titolo: record vuoto

ragazzi/e ciao a tutti vado al dunque ho un programma che lancia un
comando alla seriale dove ci sta attaccato un modem il quale risponde
al comando ricevuto fin qui tutto rego ma poi quando tento di
archiviare la stringa di risposta in un apposito database aggiunge un
nuovo record ma è vuoto e non dovrebbe esserlo vi riporto il
codice(così potete provarlo) basta guardate  il metodo serialEvent ed
aggiungi:
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
   import java.io.OutputStream;
   import java.io.IOException;
import java.io.PrintStream;
import java.sql.*;
import java.util.Timer;
import java.util.TimerTask;
   import java.util.TooManyListenersException;
   import javax.comm.*;
/**
 * Simple program to read characters from the command-line, send
 * them to the specified serial port, and echo any characters
returned.
 * Modeled after the SimpleRead and SimpleWrite sample programs
included
 * with the Java Communications API distribution.
 */
    public class SimpleReadWrite1 implements Runnable,
SerialPortEventListener
	{
   String c;
      static String DEFAULT_PORT = "COM4";
      Connection con = null;
      InputStream  in;
      OutputStream out;
      private String message = "AT\r";
     boolean t = true;
      Thread readerThread;
      SerialPort serialPort;
	protected static Object srw;
	private Object f;
	private Object fis;
      public void writeToCommPort(String message)  {
        this.message = message;
      }
    /**
     * Main method.
     */
       public static void main(String[] args) {
         String portname = DEFAULT_PORT;
         if (args.length > 1) {
            System.err.println("Usage: java SimpleReadWrite
[port_name]");
            System.exit(1);
         }
         else if (args.length == 1) {
            portname = args[0];
         }
         try {
            CommPortIdentifier portId =
CommPortIdentifier.getPortIdentifier(portname);
            if (portId.getPortType() ==
CommPortIdentifier.PORT_SERIAL) {
               SimpleReadWrite1 srw = new SimpleReadWrite1(portId);
            }
            else {
               System.err.println(portname + " is not a serial port");
               System.exit(1);
            }
         }
             catch (NoSuchPortException e) { //Port nicht vorhanden
               System.err.println("No such port: " + portname);
               System.exit(1);
            }
             catch (PortInUseException e) { //Port ist
gesperrt/inGebrauch
               System.err.println("Port in use: " + portname);
               System.exit(1);}
             }
    /**
     * Constructor.
     */
       public SimpleReadWrite1(CommPortIdentifier portId) throws
PortInUseException {
         try {
            SerialPort serialPort = (SerialPort)
portId.open("SimpleReadWrite",
                                                             2000);
//Port mit
            in  = serialPort.getInputStream();
            out = serialPort.getOutputStream();
           serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
            serialPort.setSerialPortParams(9600,
//Schnittstelleneinstellungen initialisieren
                                           SerialPort.DATABITS_8,
                                           SerialPort.STOPBITS_1,
                                           SerialPort.PARITY_NONE);
            Thread readerThread = new Thread(this);
            //readerThread.setDaemon(true);
            readerThread.start();
         } //Exception-Handling
             catch (IOException e) {
               System.err.println("Problem opening streams");
               System.exit(1);
            }
             catch (TooManyListenersException e) {
               System.err.println("Too Many Listeners");
               System.exit(1);
            }
             catch (UnsupportedCommOperationException e) {
               System.err.println("Problem setting port parameters");
               System.exit(1);
            }
      }
    /**
	 * @param b
	 */
	/**
     * This method loops forever, reading data from the
     * command line and writing it directly to the serial port.
     * No buffering is performed.
	 * @throws InterruptedException
     */
       public void run() {
         try {
            while(true){
			synchronized(this){
               out.write(message.getBytes());
          wait();
            } }
         }
             catch (IOException e) {
            // Terminate thread
            } catch (InterruptedException e) {
				// TODO Blocco catch generato automaticamente
				e.printStackTrace();
			}/*byte[] readBuffer = new byte[1];
            try {
                while (in.available() > 0) {
                   int numBytes = in.read(readBuffer);
                }
               System.out.print(new String(readBuffer));
            //   readerThread.interrupt();
       //  readerThread=null;
             }
                 catch (IOException e) {
                  // Terminate handling this event on read error
                }*/}
      /* public boolean stopThread() throws IOException{out.close();
       in.close();return t=false;}*/
    /**
     * Process serial port events.  This method is required
     * when implementing SerialPortEventListener
     *
     * @param event SerialPortEvent object to process
     */
     public void serialEvent(SerialPortEvent event) {
       	String a;
         switch (event.getEventType()) {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
               break;
            case SerialPortEvent.DATA_AVAILABLE:
                // If there is data available on serial port,
                // read it in in chunks <=20 bytes
                //
               byte[] readBuffer = new byte[1];
               try {
                  while (in.available() > 0) {
                     int numBytes = in.read(readBuffer);
                  }
                  c=new String(readBuffer);
                   aggiungi(c);
              //System.out.print(new String(readBuffer));
                 new Timer(true).schedule(new TimerTask() {
                    public void run() {
                     //System.out.println("Preparing to interrupt");
                    try{  readerThread.interrupt();
                      readerThread = null;}
                    catch(NullPointerException npe){System.exit(0);}//
to release it
                    }
                  }, 2000); // run() after 2000 milliseconds
               }
                   catch (IOException e) {
                    // Terminate handling this event on read error
                  }
               break;
            default:
               System.out.print("Unknown SerialPortEvent type = " +
                                 event.getEventType());
               break;
         }
      }
	/**
	 * @param c2
	 */
	private void aggiungi(String c2) {
		try {
      	Class.forName("com.mysql.jdbc.Driver");
	con=DriverManager.getConnection("jdbc:mysql://localhost/example"," ",
"");
      	}
      catch(Exception e) {
      	e.printStackTrace();
      	System.out.println("Exception: " + e.getMessage());
      	}
      try {Statement st = con.createStatement();
		st.executeUpdate("INSERT INTO output(risultato) VALUES ('"+c+"')");
// String   c=toString(new String(readBuffer));
	} catch (SQLException e1) {
		// TODO Blocco catch generato automaticamente
		e1.printStackTrace();
	}
		// TODO Stub di metodo generato automaticamente
	}
	/**
	 *
	 */
	/**
	 * @param string
	 */
	public String toString(String string) {System.out.print(string);
		return string;
		// TODO Stub di metodo generato automaticamente
	}
         }
 
invece di un database forse dovrei archiviarlo in un file

se provo, invece di aggiungere ad un database ad aggiungere la risposta
in un file: idem vuoto lo stesso
le righe di codice sono queste(che piazzo dove prima chiamavo il metodo
aggiungi):
 PrintWriter out = new PrintWriter( new BufferedOutputStream(new
FileOutputStream("nome.txt")));
    				  out.print(new String(readBuffer));
    				   out.close();
cioè inserisco ciò che leggo da seriale nel file nome.txt
spero in un vostro aiuto

 st.executeUpdate("INSERT INTO output(risultato) VALUES ('"+c+"')");
c2
Saluti
CarMas

si me ne sono accorto ma non cambia il risultato