Solved

Reading through a com port to a text file

Posted on 2001-08-08
5
359 Views
Last Modified: 2008-03-03
Hi lads,

I'd like to read through a com port (perhaps BufferedReader) and then write to a text file.

Any quick (AND EASY) ideas?
Thanks,
jamie
0
Comment
Question by:dubliner
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 1

Expert Comment

by:dviji
ID: 6364508
Hi,
    Try with FileInputStream and instead of file name pass the port name i.e you are using COM1 then the code should like

FileInputStream fis = new FileInputStream("COM1");

//For writing to COM also the same thing.. i.e like
FileOutputStream fis = new FileOutputStream("COM1");

(I did  for writting to COM port it works fine. So reading also it should work. Try it and let me know your result)

..dviji






0
 
LVL 15

Expert Comment

by:mohan_sekar
ID: 6364567
Hi,

       Try this link. It has got code for communication.

http://jw.itworld.com/javaworld/jw-09-1998/jw-09-indepth-2.html

:-)

cheers

Mohan


0
 
LVL 3

Expert Comment

by:modder
ID: 6367040
more suggestions from mohan_sekar from your duplicate question:

Comment
From: mohan_sekar  Date: 08/08/2001 07:57AM PST
Hi,

I hope this link would help u

http://java.sun.com/products/javacomm/index.html

bye

Mohan

Comment

From: mohan_sekar  Date: 08/08/2001 08:01AM PST

Hi again,

I hope this too would

http://library.wolfram.com/examples/JavaSerial/

:-)

bye

Mohan

Comment

From: mohan_sekar  Date: 08/08/2001 08:23AM PST

Hi again!

Here one more with CODE.

http://jw.itworld.com/javaworld/jw-09-1998/jw-09-indepth-2.html

:-)

cheers

Mohan




If any of these provide the solution, please accept Mohan's comment above this one, not this comment, as it was posted by *me*, not by Mohan.

I have deleted your duplicate questions and refunded your points.


modder
Community Support Admin
0
 
LVL 16

Expert Comment

by:Valeri
ID: 6367132
listening...
0
 

Accepted Solution

by:
mailtoycg earned 100 total points
ID: 6375662
I think you must use comm api.
and I can give you some code.maybe it can help you.
package comm;
import java.io.*;
      /**
       *
       * This class reads message from the specific serial port and save
       * the message to the serial buffer.
       *
       */
      public class ReadSerial extends Thread
      {
            private SerialBuffer ComBuffer;
            private InputStream ComPort;
                  /**
                   *
                   * Constructor
                   *
                   * @param SB The buffer to save the incoming messages.
                   * @param Port The InputStream from the specific serial port.
                   *
                   */
            public ReadSerial(SerialBuffer SB, InputStream Port)
            {
                  ComBuffer = SB;
                  ComPort = Port;
            }
            public void run()
            {
                  int c;
                  try
                  {
                        while (true)
                        {
                              c = ComPort.read();
                              ComBuffer.PutChar(c);
                        }
                  } catch (IOException e) {}
            }
      }
//----------------------------------------------
package comm;
import java.io.*;
import java.util.*;
import javax.comm.*;
/**
 *
 * This bean provides some basic functions to implement full dulplex
 * information exchange through the srial port.
 *
 */
public class SerialBean{
  static String PortName;
  CommPortIdentifier portId;
  SerialPort serialPort;
  static OutputStream out;
  static InputStream  in;
  SerialBuffer SB;
  ReadSerial   RT;
 /**
  *
  * Constructor
  *
  * @param PortID the ID of the serial to be used. 1 for COM1,
  * 2 for COM2, etc.
  *
  */
                  public SerialBean(int PortID)
                  {
                        PortName = "COM" + PortID;
                  }
                  /**
                   *
                   * This function initialize the serial port for communication. It startss a
                   * thread which consistently monitors the serial port. Any signal capturred
                   * from the serial port is stored into a buffer area.
                   *
                   */
                  public int Initialize()
                  {
                        int InitSuccess = 1;
                        int InitFail    = -1;
                  try
                  {
                        portId = CommPortIdentifier.getPortIdentifier(PortName);
                        try
                        {
                              serialPort = (SerialPort)
                              portId.open("Serial_Communication", 2000);
                        } catch (PortInUseException e)
                        {
                              return InitFail;
                        }
                        //Use InputStream in to read from the serial port, and OutputStream
                        //out to write to the serial port.
                        try
                        {
                              in  = serialPort.getInputStream();
                              out = serialPort.getOutputStream();
                        } catch (IOException e)
                        {
                              return InitFail;
                        }
                        //Initialize the communication parameters to 9600, 8, 1, none.
                        try
                        {
                               serialPort.setSerialPortParams(9600,
                                                SerialPort.DATABITS_8,
                                                SerialPort.STOPBITS_1,
                                                SerialPort.PARITY_NONE);
                        } catch (UnsupportedCommOperationException e)
                        {
                              return InitFail;
                        }
                  } catch (NoSuchPortException e)
                  {
                        return InitFail;
                  }
                  // when successfully open the serial port,  create a new serial buffer,
                  // then create a thread that consistently accepts incoming signals from
                  // the serial port. Incoming signals are stored in the serial buffer.
                  SB = new SerialBuffer();
                  RT = new ReadSerial(SB, in);
                  RT.start();
                  // return success information
                  return InitSuccess;
                  }
                  /**
                   *
                   * This function returns a string with a certain length from the incomin
                   * messages.
                   *
                   * @param Length The length of the string to be returned.
                   *
                   */
                  public String ReadPort(int Length)
                  {
                        String Msg;
                        Msg = SB.GetMsg(Length);
                        return Msg;
                  }
                  /**
                   *
                   * This function sends a message through the serial port.
                   *
                   * @param Msg The string to be sent.
                   *
                   */
                  public void WritePort(String Msg)
                  {
                        int c;
                        try
                        {
                              for (int i = 0; i < Msg.length(); i++)
                                    out.write(Msg.charAt(i));
                        } catch (IOException e)  {}
                  }
                  /**
                   *
                   * This function closes the serial port in use.
                   *
                   */
                  public void ClosePort()
                  {
                        RT.stop();
                        serialPort.close();
                  }
      }
//---------------------------------------------
package comm;

      /**
       *
       * This class implements the buffer area to store incoming data from the serial
       * port.
       *
       */
      public class SerialBuffer
      {
            private String Content = "";
            private String CurrentMsg, TempContent;
            private boolean available = false;
            private int LengthNeeded = 1;
                  /**
                   *
                   * This function returns a string with a certain length from the incomin
                   * messages.
                   *
                   * @param Length The length of the string to be returned.
                   *
                   */
            public synchronized String GetMsg(int Length)
            {
                  LengthNeeded = Length;
                  notifyAll();
                  if (LengthNeeded > Content.length())
                  {
                        available = false;
                        while (available == false)
                        {
                              try
                              {
                                    wait();
                              } catch (InterruptedException e) { }
                        }
                  }
                  CurrentMsg  = Content.substring(0, LengthNeeded);
                  TempContent = Content.substring(LengthNeeded);
                  Content = TempContent;
                  LengthNeeded = 1;
                  notifyAll();
                  return CurrentMsg;
            }
                  /**
                   *
                   * This function stores a character captured from the serial port to the
                   * buffer area.
                   *
                   * @param t The char value of the character to be stored.
                   *
                   */
            public synchronized void PutChar(int c)
            {
                  Character d = new Character((char) c);
                  Content = Content.concat(d.toString());
                  if (LengthNeeded < Content.length())
                  {
                        available = true;
                  }
                  notifyAll();
            }
      }
//--------------------------------------------
package comm;

import java.io.*;
      /**
       *
       * This is an example of how to use the SerialBean. It opens COM1 and reads
       * six messages with different length form the serial port.
       *
       */
      public class SerialExample{
            public static void main(String[] args)
            {
                  //TO DO: Add your JAVA codes here
                  SerialBean SB = new SerialBean(2);
                  String Msg;
                  SB.Initialize();
     
                  for (int i = 5; i <= 10; i++)
                  {
                        Msg = SB.ReadPort(i);
//** Hi notice here you get the msg for comm port .
//write the msg to a txt file is very easy.
//good luck!! :)
                        //SB.WritePort("Reply: " + Msg);
                  }
     
                  SB.ClosePort();
            }
      }


0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question