Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.List;
import javax.smartcardio.Card;

import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;

import javax.smartcardio.TerminalFactory;

public class Main {
    /**
     * Establishes the connection with the Smart Card (if present)
     * using the first available terminal.
     */
    public static Card connectCard() throws CardException {
        // Get available terminals
        List<CardTerminal> terminals = TerminalFactory.getDefault().terminals().list();
        if (terminals.size() < 1) {
            throw new CardException("No attached Smart Card terminals found");
        }

        // Search for connected cards
        Card card = null;
        for (CardTerminal terminal : terminals) {
            if (terminal.isCardPresent()) {
                card = terminal.connect("*");
                break;
            }
        }
        if (card == null) {
            throw new CardException("No connected Smart Cards found");
        }

        return card;
    }
}