The. properties file is a resource file, and java is often used to access the resource file. The following example uses the. properties file as an example to show you how to access the resource file in java.
Today, I will organize a java resource access file for you.
The accessed file type is. properties.
Detailed ideas:
Use the stream to read the. properties file and encapsulate it into the Properties object. Obtain the value according to the getProperty () method in the Properties object. The parameter in the brackets is the value name.
The Code is as follows: |
Copy code |
Import java. io. FileInputStream; Import java. io. FileOutputStream; Import java. util. Properties;
Public class PropertyEditor { Public static void main (String [] args) throws Exception { Properties prop = new Properties (); // property set object FileInputStream FCM = new FileInputStream ("prop. properties"); // attribute file input stream (with the package name "src/prop. properties" added relative to the file name under the root directory ") Prop. load (FS); // load the property file stream to the Properties object FCM. close (); // close the stream
// Obtain the property value. sitename is defined in the file. System. out. println ("Get attribute value: sitename =" + prop. getProperty ("sitename ")); // Obtain the property value. country is not defined in the file. A default value is returned in this program, but the attribute file is not modified. System. out. println ("Get attribute value: country =" + prop. getProperty ("country", "China "));
// Modify the attribute value of sitename Prop. setProperty ("sitename", "China "); // Add a new property studio Prop. setProperty ("studio", "Boxcode Studio "); // File output stream FileOutputStream fos = new FileOutputStream ("prop. properties "); // Save the Properties set to the stream Prop. store (fos, "Copyright (c) Boxcode Studio "); Fos. close (); // close the stream } } |
Resource file storage:
Sitename = u4E2Du56FD
Siteurl = www. bKjia. c0m
Studio = Boxcode Studio