First step: Establish Jdbc.properties first
1 User = Root 2 Password=1234563 url=mysql:jdbc://localhost:3306 /yanlong4 driver=Com.mysql.jdbc.Driver
View CodeThe first way: direct file read
1 Packagecom.mon11.day14;2 3 ImportJava.io.File;4 ImportJava.io.FileInputStream;5 Importjava.io.FileNotFoundException;6 ImportJava.io.InputStream;7 Importjava.util.Properties;8 9 /** Ten * Class Description: 1. Read directly from the file One * @authorAuthor: Administrator A * @versionCreation Date: November 14, 2017 - */ - Public classtestproperties { the - Public Static voidMain (string[] args) { - /*The Propertiesproperties class represents a persistent set of properties. - Properties can be saved in a stream or loaded from a stream. + each key and its corresponding value in the property list is a string. */ - +Properties properties=NewProperties ();//instantiating an object A atFile file=NewFile ("Src/jdbc.properties");//Open File - - Try { -InputStream inputstream=NewFileInputStream (file);//Open the file's interface - properties.load (inputstream); -}Catch(Exception e) { in //TODO auto-generated Catch block - e.printstacktrace (); to } + - //Output theSystem.out.println (Properties.get ("User")); *System.out.println (Properties.get ("Password")); $System.out.println (properties.get ("url"));Panax NotoginsengSystem.out.println (Properties.get ("Driver")); - the } +}
View CodeOperating effect:
Second way: Read through the ClassLoader (project development with this, large project)
1 Packagecom.mon11.day14;2 3 ImportJava.io.File;4 ImportJava.io.FileInputStream;5 Importjava.io.FileNotFoundException;6 Importjava.io.IOException;7 ImportJava.io.InputStream;8 Importjava.util.Properties;9 Ten /** One * Class Description: 1. Direct class loader Read A * @authorAuthor: Administrator - * @versionCreation Date: November 14, 2017 - */ the Public classTestProperties2 { - - Public Static voidMain (string[] args) { - /*The Propertiesproperties class represents a persistent set of properties. + Properties can be saved in a stream or loaded from a stream. - each key and its corresponding value in the property list is a string. */ + AProperties properties=NewProperties ();//instantiating an object at - //loading through the class loader - Try { -Properties.load (TestProperties2.class. getClassLoader (). getResourceAsStream ("Jdbc.properties")); - //getClassLoader () returns the class loader for this class. - //getResourceAsStream (String name) finds the resource with the given name. in}Catch(IOException e) { - //TODO auto-generated Catch block to e.printstacktrace (); + } - //Output theSystem.out.println (Properties.get ("User")); *System.out.println (Properties.get ("Password")); $System.out.println (properties.get ("url"));Panax NotoginsengSystem.out.println (Properties.get ("Driver")); - the } +}
View CodeOperating effect:
Two ways to read database configuration information (future development projects with a Java linked database)-------Java Fundamentals