如何从 Java 中的 InputStream 打开 MS Access 文件?

How to open an MS Access file from an InputStream in Java?

我已经使用 net.ucanaccess.jdbc.UcanaccessDriver 从 MS Access 读取数据:

public static void main(String[] args) {
    try {
        Statement statement = getConnection().createStatement();
        ResultSet resultSet = statement.executeQuery(" select * from students ");
        while (resultSet.next()) {
            String log = resultSet.getLong("id") + " - " + resultSet.getString("name") + " - " + resultSet.getString("family");
            System.out.println(log);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

public static Connection getConnection() {
    Connection connection = null;

    try {
        File f = new File("files/access.accdb");
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        connection = DriverManager.getConnection("jdbc:ucanaccess://" + f.getAbsolutePath());
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return connection;
}

但是现在,我想从 MS Access 读取数据 InputStream,可能是这样的:

public static Connection getConnection() {
    Connection connection = null;

    try {
        File f = new File("files/access.accdb");
        InputStream inputStream = new FileInputStream(f);
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        connection = DriverManager.getConnection(inputStream); /*Changed*/
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return connection;
}

不,您不能使用 UCanAccess 直接从 InputStream 打开 Access 数据库。但是,您可以使用 java.nio.Files.copy 将 InputStream 复制到一个临时文件,然后让 UCanAccess 打开它。