我正在尝试将Eclipse中的Java项目保存为jar文件。
当我正在使用Access数据库并且我应该导出所有内容时,我决定将数据库文件包含在与Main.class
和SingletonConnection.class
相同的文件夹中(这是管理连接的类)与数据库)。
所以代码是:
private SingletonConnection()throws ConnessioneException{
idConnection = "root";
passConnection = "";
String slash="\\";
String path=this.getClass().getResource("").getPath().replaceFirst("^.*:", "").replaceFirst("!.*$", "").replace("/", slash.concat("\\"));
System.out.println("path è "+path);
driverConnection = "sun.jdbc.odbc.JdbcOdbcDriver";
stringConnection = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=C:"+path+"eventi.mdb";
try {
Class.forName(driverConnection);
conn = DriverManager.getConnection(stringConnection,idConnection,passConnection);
} catch (Exception e) {
e.printStackTrace();
throw new ConnessioneException();
}
}
public static Connection getInstance()throws ConnessioneException{
if(conn==null)
new SingletonConnection();
return conn;
}
在Eclipse中一切正常。该项目工作,没有例外,但当我尝试将项目导出为Runnable Jar文件或Jar文件时,它总是返回ConnessioneException =null
,因此与db的连接失败。
方法getInstance中给出了异常,“new SingletonConnection()”
行我需要在其他PC上运行该程序,所以我需要解决这个问题。我无法继续使用Eclipse。
答案 0 :(得分:0)
解决:也许这对某人有用:
*** import org.apache.commons.io.IOUtils; !! (package: commons-io-2.1.jar)
idConnection = "root";
passConnection = "";
String slash="\\";
String path=null;
String temp=System.getProperty("java.io.tmpdir");
if ( !(temp.endsWith("/") || temp.endsWith("\\")) )
temp = temp + System.getProperty("file.separator");
File tempDir = new File(temp);
File temporaryFile = new File(tempDir, "templateCopy.mdw");
InputStream templateStream = getClass().getResourceAsStream("eventi.mdw");
try {
IOUtils.copy(templateStream, new FileOutputStream(temporaryFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
//Dialog d1=new Dialog("filenotfound");
} catch (IOException e1) {
e1.printStackTrace();
//Dialog d2=new Dialog("io");
}catch (Exception e1){
//Dialog d3=new Dialog("general");
}
path = temporaryFile.getAbsolutePath();
driverConnection = "sun.jdbc.odbc.JdbcOdbcDriver";
stringConnection = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+path;
try {
Class.forName(driverConnection);
conn = DriverManager.getConnection(stringConnection,idConnection,passConnection);
} catch (Exception e) {
e.printStackTrace();
throw new ConnessioneException(e.getStackTrace());
}