Java Read username, password and port from properties file


 

Java Read username, password and port from properties file

In this section, you will come to know how to read username, password and port no from the properties file and display the data from the database.

In this section, you will come to know how to read username, password and port no from the properties file and display the data from the database.

Java Read username, password and port from properties file

In this section, you will come to know how to read username, password and port no from the properties file and display the data from the database. Now to load the data from the properties file, we have used Properties class. This class allowed us to save data to a stream or loaded from a stream using the properties file. In the properties file, data has been stored as a key value pair in the form of string.

load() - This method reads a property list (key and element pairs)from the input stream.

getProperty() - This method searches for the property with the specified key in the properties file.

data.properties file

username=root
password=root
port=3306

Here is the code:

import java.io.*;
import java.sql.*;
import java.util.*;

class UsePropertiesFile {
	public static void main(String[] args) throws Exception {
		Properties prop = new Properties();

		prop.load(new FileInputStream("data.properties"));
		String user = prop.getProperty("username");
		String pass = prop.getProperty("password");
		String port = prop.getProperty("port");

		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:"
				+ port + "/test", user, pass);
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery("Select * from data");
		while (rs.next()) {
			System.out.println(rs.getString(1) + " " + rs.getString(2));
		}

	}
}

Output:

1 Angelina
2 Martina

Ads