以下是使用Java语言和ACR122U-A9读取NFC卡片7字节UID的示例代码:
import java.util.Arrays;
import javax.smartcardio.CardException;
import javax.smartcardio.TerminalFactory;
import javax.smartcardio.Card;
import javax.smartcardio.CardChannel;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
public class NFCReader {
public static void main(String[] args) {
// 获取智能卡终端列表
try {
TerminalFactory factory = TerminalFactory.getDefault();
List terminals = factory.terminals().list();
// 获取第一个智能卡终端
CardTerminal terminal = terminals.get(0);
// 等待卡片插入
while (true) {
if (terminal.isCardPresent()) {
break;
}
}
// 获取智能卡
Card card = terminal.connect("*");
CardChannel channel = card.getBasicChannel();
// 发送APDU指令读取卡片UID
byte[] command = new byte[] { (byte)0xFF, (byte)0xCA, (byte)0x00, (byte)0x00, (byte)0x07 };
CommandAPDU apdu = new CommandAPDU(command);
ResponseAPDU response = channel.transmit(apdu);
// 获取卡片UID并以十六进制字符串格式输出
if (response.getSW() == 0x9000) {
byte[] uid = Arrays.copyOfRange(response.getBytes(), 0, 7);
String uidStr = javax.xml.bind.DatatypeConverter.printHexBinary(uid);
System.out.println("卡片UID: " + uidStr);
} else {
System.out.println("APDU指令发送失败");
}
// 断开智能卡连接
card.disconnect(true);
} catch (CardException e) {
e.printStackTrace();
}
}
}