I would like to improve my code so that it would be possible to connect to the database using a text file, but not setting the database connection from the IntelliJ or Eclipse view only from the text file (we set the login, password, path, etc. there).
public class SQL {
public static Connection Connect() throws ClassNotFoundException, SQLException, IOException {
Properties props = new Properties();
FileInputStream in = new FileInputStream("loc:/xyz.txt");
props.load(in);
in.close();
The problem is with this line:
FileInputStream in = new FileInputStream("loc:/xyz.txt")
How can I set the path to the FileInputStream
with a txt file?
So far, I can set the login, password and URL using a text file, but I still have a problem how to correctly pass the address of this text file (in a text file)
By convention, java properties files have the .properties
extension. I would suggest that you name the file jdbcconn.properties
. Put that file in the same folder as file SQL.class
. Then in your java code you can do something like the following.
Properties props = new Properties();
java.io.InputStream is = getClass().getResourceAsStream("jdbcconn.properties");
props.load(is);
Refer to javadoc of class java.lang.Class
Note that in Eclipse IDE, you create the jdbcconn.properties
file in the same folder as file SQL.java
and when you build your project, Eclipse will automatically copy file jdbcconn.properties
to the same folder as file SQL.class