Search code examples
javams-accessjdbcinputstreamucanaccess

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


I have using net.ucanaccess.jdbc.UcanaccessDriver to read data from 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;
}

but now, i want to read data from MS Access as InputStream, may be something like this:

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;
}

Solution

  • No, you cannot use UCanAccess to open an Access database directly from an InputStream. However, you could use java.nio.Files.copy to copy the InputStream to a temporary file and then get UCanAccess to open that.