这个字符串的编码是什么?

时间:2015-02-13 06:56:28

标签: java character-encoding serial-port

我试图从串口写出这个字符串,我得到一个错误java.io.UnsupportedEncodingException:* 995R15,67,3#。据我所知,这只是ASCII字符?谁能告诉我为什么会出现这个错误?

我已经编辑了我的问题以包含所有内容,以防出现其他问题。第一个是EBIAlarm.java

import java.io.*;

import javax.swing.*;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


public class EBIAlarm extends javax.swing.JFrame {

public TwoWaySerialComm twoWaySerCom;
public TwoWaySerialComm.SerialWriter serialWriter;


public EBIAlarm() {
    initComponents();
    twoWaySerCom = new TwoWaySerialComm();



    try {

        twoWaySerCom.connect("COM7");
    } 
    catch (Exception e) {

        e.printStackTrace();
        }
}



private void initComponents() {

    jTextArea1 = new javax.swing.JTextArea();
    jTextArea2 = new javax.swing.JTextArea();
    jScrollPane1 = new javax.swing.JScrollPane();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jTextArea1.setColumns(60);
    jScrollPane1.setViewportView(jTextArea2);




    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Alarm Generator");

    jTextArea1.setText("Enter custom string here");
    jTextArea2.setText("Result");
    jButton1.setText("Alarm 1");
    jButton2.setText("Alarm 2");
    jButton3.setText("Alarm 3");
    jButton4.setText("Custom Alarm");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()               

                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)    
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jTextArea1)
                    .addComponent(jTextArea2)
                    .addComponent(jScrollPane1)


    )));
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()

            .addComponent(jButton1)
            .addGap(20)
            .addComponent(jButton2)
             .addGap(20)
            .addComponent(jButton3)
             .addGap(20)
            .addComponent(jButton4)
            .addGap(20)
            .addComponent(jTextArea1)
            .addGap(20)
            .addComponent(jTextArea2)
            .addContainerGap(0,0))
            .addComponent(jScrollPane1)
    );

    pack();

    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt){
            jButton1ActionPerformed(evt);
        }

        private synchronized void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextArea1.setText("Alarm 1 Activated, String: "+alarm1);
            try {
                alarm1.getBytes(alarm1);
                serialWriter.out.write(alarm1.getBytes("US-ASCII"));
            } catch (IOException e) {
                // Do something to handle the exception
                e.printStackTrace();
            }
        }

    });

    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }

        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextArea2.setText("Alarm 2 Activated, String: "+alarm2);
        }
    });

    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }

        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextArea2.setText("Alarm 3 Activated, String: "+alarm3);
        }
    });

    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }

        private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextArea2.setText("Custom alarm, string sent: "+jTextArea1.getText ());
        }
    });
}


public static void main(String args[]) {        

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new EBIAlarm().setVisible(true);


        }
    });


}



    private void updateTextArea(final String text) {
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              jTextArea2.append(text);
            }
          });
        }
    private void redirectSystemStreams() {
          OutputStream out = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
              updateTextArea(String.valueOf((char) b));
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
              updateTextArea(new String(b, off, len));
            }

            @Override
            public void write(byte[] b) throws IOException {
              write(b, 0, b.length);
            }
          };

          System.setOut(new PrintStream(out, true));
          System.setErr(new PrintStream(out, true));
        }

// Variables declaration                    
private static javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JTextArea jTextArea1;
public javax.swing.JTextArea jTextArea2;
private javax.swing.JScrollPane jScrollPane1;
String alarm1 = "*995R15,67,3#";
String alarm2 = "*993R03,67,6#";
String alarm3 = "*994R14,67,1#";

// End of variables declaration                   
}

这是TwoWaySerialComm.java

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;





public class TwoWaySerialComm {
public TwoWaySerialComm()

{
    super();
}

void connect ( String portName ) throws Exception
{

    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if ( portIdentifier.isCurrentlyOwned() )
    {

        System.out.println("Error: Port is currently in use");
    }
    else
    {
        CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

        if ( commPort instanceof SerialPort )
        {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

            InputStream in = serialPort.getInputStream();
            OutputStream out = serialPort.getOutputStream();

            (new Thread(new SerialReader(in))).start();
            (new Thread(new SerialWriter(out))).start();

        }
        else
        {
            System.out.println("Error: Only serial ports are handled by this.");
        }
    }     
}

/** */
public static class SerialReader implements Runnable 
{
    InputStream in;

    public SerialReader ( InputStream in )
    {
        this.in = in;
    }

    public void run ()
    {
        byte[] buffer = new byte[1024];
        int len = -1;
        try
        {
            while ( ( len = this.in.read(buffer)) > -1 )
            {
                System.out.print(new String(buffer,0,len));

            }
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }            
    }
}

/** */
public static class SerialWriter implements Runnable 
{
    OutputStream out;

    public SerialWriter ( OutputStream out )
    {
        this.out = out;
    }

    public void run ()
    {
        try
        {                
            int c = 0;
            while ( ( c = System.in.read()) > -1 )
            {
                this.out.write(c);
            }                
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }            
    }
}



}

2 个答案:

答案 0 :(得分:2)

由于此行,您收到UnsupportedEncodingException,您应将其从代码中排除:

alarm1.getBytes(alarm1);

getBytes(String charsetName)方法在java.lang.String中定义如下:

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException {
    if (charsetName == null) throw new NullPointerException();
    return StringCoding.encode(charsetName, value, 0, value.length);
}

您将alarm1传递给getBytes方法作为参数,但其值不是有效的字符集。

答案 1 :(得分:0)

我最终使用下面的工作。它对我来说似乎很好。

感谢您的协助。

try {
                byte[] b = alarm2.getBytes("ASCII");

                TwoWaySerialComm.SerialWriter sw = new       TwoWaySerialComm.SerialWriter(
                        twoWaySerCom.serialPort.getOutputStream());

                sw.out.write(b);
            } catch (IOException e) {
                // Do something to handle the exception
                e.printStackTrace();
            }