java - 这个字符串是什么编码?

标签 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();
        }            
    }
}



}

最佳答案

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

alarm1.getBytes(alarm1);

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

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

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

关于java - 这个字符串是什么编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28494096/

相关文章:

java - JSONObject 不可序列化?

java - 如何从 javascript sdk 获取 facebook 结果到 java

character-encoding - Shift_JIS 中的反斜杠和波浪号字符是否有正确的编码?

javascript - Sublime Linter 插件不适用于 Windows,来自西里尔字母的问候

java - Rijndael AES、addRoundKey、异或十六进制字符串并将它们存储为字节

java - Java 中的字数统计

java - 汉字编码?

c++ - 从串口读取数据时出错

java - Arduino 与 Java 接口(interface)问题

serial-port - screen /dev/ttyUSB0 具有不同的选项,例如数据位、奇偶校验等