I have a sqlite database file that i am accessing using a swing aplication. The jdbc driver and everyhting works. If i get the exact file location and paste it into the database url it will work. I tried using a relative file path and it does not work. I created a method to get the direct file path to the working directory of the program and craeted a map if you will of the folder and its contents. it should work, but doesn't, i was wondering if anyone could tell me why. here is the method
public String GetAbsPath(){
File workingDir=new File(".");
String absolute=workingDir.getAbsolutePath();
char[] absA=absolute.toCharArray();
ArrayList<String> list=new ArrayList<>();
for (int x = 0; x < absA.length; x++) {
String listPiece = Character.toString(absA[x]);
list.add(listPiece);
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < list.size()-1; i++) {
if(list.get(i).equals("\\")){
list.set(i, "\\\\");
}
result.append(list.get(i));
}
String path=result.toString();
return path;
}
it returns the exact file path that i enter in manually, but will not find the file. both methods work with netbeans but only entering in the exact file path into a string works when i try to run the file outside of netbeans. This is where the method is called.
GetPath dir=new GetPath();
String dirFilePath = "jdbc:sqlite:"+dir.GetAbsPath()+"Office.sqlite";
database=dirFilePath;
This worked...
CodeSource codeSource = MainFrame.class.getProtectionDomain().getCodeSource();
File jarFile=null;
String jarDir=null;
try {
jarFile = new File(codeSource.getLocation().toURI().getPath());
jarDir = jarFile.getParentFile().getPath();
} catch (URISyntaxException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
database ="jdbc:sqlite:"+jarDir +"\\Office.sqlite";