It is s not advisable to hard code the values in a java programming. The efficient way of doing it is by using Properties file , which actually store static information in key and value pair.
1.Loading a propertied file present in the System location
import java.io.*;
import java.util.*;
public class ReadPropertiesFile {
public static void main(String[] args) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("C:/data.properties"));
String name = prop.getProperty("name");
String address = prop.getProperty("address");
System.out.println("Name: " + name);
System.out.println("Address: " + address);
} catch (Exception e) {
}
}
}
import java.util.*;
public class ReadPropertiesFile {
public static void main(String[] args) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("C:/data.properties"));
String name = prop.getProperty("name");
String address = prop.getProperty("address");
System.out.println("Name: " + name);
System.out.println("Address: " + address);
} catch (Exception e) {
}
}
}
2.Loading a properties file present in java package
import java.io.IOException;import java.io.InputStream;import java.util.Properties;import java.util.ResourceBundle;public class LoadPropertiesExample { private Properties configProp = new Properties(); public static void main(String[] args) { InputStream in = this.getClass(). getResourceAsStream("/com/csc/config/config.properties"); try { configProp.load(in); } catch (IOException e) { e.printStackTrace(); } System.out.println(configProp.getProperty("name")); }}
No comments:
Post a Comment