Access WebContent folder file in java class - java

I'm developing a web application with sqlite database. While developing the application, I created the database connection in a java class. There I've mentioned my url as like below
String url = "jdbc:sqlite:D:\\Database\\profileDB.db";
I want to place the db file from that location to specific location inside my Webcontent folder say resources.
Now I want to change my URL pointing to folder file.
Webcontent/resources/profileDB.db
.
Anyone kindly suggest me how to do this. For the information, I'm not using any servlet in creating the connection, it is just a normal java class.

I dont know about the SQLite database but if you just want the url to the db file the you can use getResource("name_of _the resource") method of the Class class. it gives you the URL of the named resource. the rules for searching for the resource depends upon the classloader used to load the class.
for eg : my package(folder) structure is :
test-
|-foo.class
|-image.png
then inside foo.class
URL url = getClass().getResource("image.png");
it will give the url to the image.png

IMHO, you need to add sqlite.jar in Project Properties -> Java Build Path -> Libraries -> Add External Jar.
Then you can try connecting using:
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("JDBC:sqlite:sample.db");
} catch (Exception e) {
e.printStackTrace();
}
You can refer this link for sqlite jdbc

Related

How to connect to a database located inside project folder

Maybe it's a silly question, but I am new to databases and I don't know how to do this.
I have the following line of code that I use in order to connect to a database located in my D: drive. How can I change it so it connects to the database if the database is located inside the project folder?
(I use netbeans IDE)
Connection conn = DriverManager.getConnection("jdbc:sqlite:d:\\Databases\\DataBase1.db");
//I don't want an exact path, I need it so it works idependetly of where the project folder is located
According to this answer:
In your code you can use a relative path and it should be relative to the top of your project's directory. In NetBeans' Databases Service you will need to either use an absolute path to connect to the database that exists (in your project) or you will need to provide a relative path...
So according the SQLite Tutorial connection string should be as follows:
jdbc:sqlite:DataBase1.db

Connect to a SQlite file inside a .jar file with JDBC? [duplicate]

I have created a Swing application that uses SQLite as a local database. The database file is located in project's root directory.
Project/DatabaseFile
The application runs fine on Eclipse, but when I run the packaged executable Jar, I get the following error:
No such table : table1
This means that the database is not reachable. When I examined the contents of the resulting JAR file, the database file was not there anymore.
In the code, I've linked the database as follows:
jdbc:sqlite:DatabaseFile
My question is, how to include the SQLite database in the executable Jar?
EDIT
When I placed the DB file in the source Folder Project/src/DatabaseFile and changed the path to jdbc:sqlite:src/DatabaseFile, it worked on Eclipse but again when running the Jar file as java -jar Project.jar. It said:
path to 'src/DatabaseFile': 'C:\Users\name\src' does not exist
I think I need to specify a relative path for the database.
EDIT
This is how I connect to the database:
public Connection getConnection(){
try{
Class.forName("org.sqlite.JDBC").newInstance();
con = DriverManager.getConnection("jdbc:sqlite:src/DatabaseFile");
} catch (Exception e) {
Log.fatal("Méthode: getConnection() | Class : SQLiteConnection | msg system : " + e.getMessage());
}
return con;
}
What library are you using for SQLite?
I did a search based on the connection URI you indicated and found this one. In the documentation it says:
2009 May 19th: sqlite-jdbc-3.6.14.1 released. This version supports "jdbc:sqlite::resource:" syntax to access read-only DB files contained in JAR archives, or external resources specified via URL, local files address etc. (see also the detailes)
If that is the driver you are using, then I would suggest the following connection URI:
"jdbc:sqlite::resource:DatabaseFile"
The key is that since your database is in a jar file, it can not be access as a file with FileInputStream. Instead it must be accessed through the JVM's support for it (namely with Class.getResource() or Class.getResourceAsStream()). Do note that resources contained within jar files are read-only. You won't be able to save any changes to your database.
I have found two different ways to name the filepath depending on how you are trying to access it. Assuming you are accessing the db is located in /yourproject/resource/ or /yourproject/bin/resource ( havent narrowed it down, mine is in both and I'm happy with it) you should use this as your path:
//Eclipse test path
String url = "jdbc:sqlite:resource/mydb.db";
or
//runnable jar path
String url = "jdbc:sqlite::resource:mydb.db";
then
mysqlitedatasource.setUrl(url);
Your way also works... by putting the db in /src

How to use a .properties file in Eclipse Java Dynamic Web Project?

I'm developing a Dynamic Web Project in Eclipse. I created a .properties file for store database details (Username, Password etc.). I added it by right clicking on the project and New -> File . I used the Java util package Properties class. But it does not working. I can not retrieve any property from the file. Here is the code I used,
Properties prop = new Properties();
try {
prop.load(new FileInputStream("database.properties"));
String db = prop.getProperty("database");
String userName = prop.getProperty("dbuser");
String password = prop.getProperty("dbpassword");
} catch (IOException ex) {
ex.printStackTrace();
}
Is there something wrong or Is there any particular place where I should put properties file.
What you did is correct, ie right clicking the project and new--file.You have to Put your properties where you start your jvm from. Please look into the attached image. The properties file is marked in red. Look if your properties file is also located something like this.
Also add this in your code to find out where to put your file:
System.out.println(new File(".").getAbsolutePath());
For more details please follow this link- FileNotFoundException when using java properties file
Normally, you make sure the properties file is in the project runtime classpath (e.g. WEB-INF/classes) and then load it using either the System classloader or the property file handler's classloader, i.e. (Freehand typing from memory -- NOT COMPILED)
try{
Properties p = new Properties();
InputStream in = MyPropertyHandler.getClass()
.getClassLoader()
.getResourceAsStream("com/package/props/database.properties");
p.load(in);
catch(IOException e){
e.printStackTrace(System.err);
}
I'm betting you aren't pointing at the correct location. Make sure you're properties file is in the correct place. Using that code, I believe it is looking for ${CURRENT_WORKING_DIR}/database.properties, which is the case of a web app in eclipse is WEB-INF/classes (i think).
You should instead be using the more portable java.util.Properties#load(InputStream) with the result of javax.servlet.ServletContext#getResourceAsStream(String).
Try to give absolute path or relative path to the proprty file, also check this propery file path has been add to source folders or not, if not it will not be copied to your classes folder. (Right cclick on project , check java build path under source tab.
You should have .properties file in same package as class that is using it.
Or better, read properties file with getResourceAsStream method (otherwise you can have some problem later when you'll have file in .war archive).
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("database.properties");

Java: getCodeBase() on non-applet application

I'm trying to create a URL to access a local file like so:
URL myURL = new URL(getCodeBase(), "somefile.txt");
But it throws a NullPointerException when it attempts getCodeBase(). I'm fairly certain that the reason behind this is because the class file that this code belongs to is not an applet. Is there any way I can get the code base without using an applet? I just want to access a local file without having to put the actual directory in (because when others run the application the directory path will obviously not be the same).
I would use the following to be relative to the working directory
URL myURL = new URL("file:somefile.txt");
or
URL myURL = new URL("file", "", "somefile.txt");
or
File file = new File("somefile.txt");
You don't need to get the code base.
If the file resides on your classpath (this includes the path where your classes are deployed), you can access vía the ClassLoader method getSystemResource.
URL myURL = ClassLoader.getSystemResource("somefile.txt");
If somefile.txt is read-only, put it in a Jar that is on the run-time class-path of the application. Access it using:
URL urlToText = this.getClass().getResource("/path/to/somefile.txt");
If it is read/write:
Check a known sub-directory of user.home for the file.
If not there, put it there (extracting it from a Jar).
Read/write to the file with known path.
See How to create a folder in Java posting, which asked very similar question.
As Tomas Narros said above, the proper way to do this is to use the ClassLoader to locate resource files in the Classpath. The path you pass to the ClassLoader is relative to the classpath that was set when you started the Java app.
If you browse the above link, you'll see some sample code showing how to resolve the path to a file in your classpath.

java- jar file cannot find resources

I 'm working on a java application and in the program I use some files such as images, a local database and an .htm file (used as help file).
I have tried to make the access to these resources, location independent. So I've made in the package that contains my source files, a subfolder named resources and I've put there all these images,etc. I access them through .getResource() method, and not by using paths. For example that's how i access an image resource:
lang_icon=new javax.swing.ImageIcon(getClass().getResource("/myeditor/resources/checked.gif"));
The problem is that when the .jar file is built, it doesn't work properly. It loads the images successfully but cannot connect to the local database or open the .htm file.
Here is the code I use to access the .htm file (it works fine when I run the application through Netbeans)
URL helpFile= getClass().getResource("/myeditor/resources/help/help.htm");
try {
BrowserLauncher launcher = new BrowserLauncher();
launcher.openURLinBrowser(helpFile.toString());
} catch (BrowserLaunchingInitializingException ex) {
Logger.getLogger(mainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedOperatingSystemException ex) {
Logger.getLogger(mainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
and here is the code I use to access my local database
URL url = getClass().getResource("/myeditor/resources/icddb");
database = new File(url.getFile());
try
{
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:file:" + database+"\\icddb", "sa", "");
When I try to open the .htm file through .jar file it shows this error "This file does not have a program associated with it for performing this action. Create an association in the Folder Options in control panel".
When I try to connect to my local database it says "Severe could not reopen database".
All ideas appreciated!
Thank you and sorry for my english!
Can you print out the URL you're asking the browser to open ? That should give a clearer indication as to what's going on.
I suspect the URL you're getting from getResource() is a URL pointing to within your .jar file. As such the browser is going to have difficulty opening that. I would (perhaps) extract that file to a temporary directory and have the browser open that.

Categories