JAVA 53rd-IO stream (7) File object exercises & amp; Properties set

Source: Internet
Author: User

JAVA 53rd-IO stream (7) File object exercises & amp; Properties set

I. Exercises

In-depth folder Traversal

Deep traversal naturally comes to mind recursion, and Recursion naturally comes to mind that its underlying algorithm is stack.

List all contents in a specified directory (including sub-Directories)

PS: Do not traverse drive C

Import java. io. *; public class Main {public static void main (String [] args) throws IOException {File dir = new File ("D: \ ACM training"); ListAllDemo (dir, 0);} public static void ListAllDemo (File dir, int level) throws IOException {System. out. println (GetSpace (level) + "folder:" + dir. getAbsolutePath (); level ++; // For indent // obtain all the current files in the specified directory/File object File [] files = dir. listFiles (); for (int I = 0; I
 
  
Delete directory

Import java. io. *; public class Main {public static void main (String [] args) throws IOException {File dir = new File ("D: \ ACM training 1"); // dir. delete (dir); if the File contains content, it cannot be deleted from the root directory. You must delete DeleteDemo (dir);} public static void DeleteDemo (File dir) {File [] files = dir. listFiles (); for (File f: files) {if (f. isDirectory () {DeleteDemo (f);} else {System. out. println (f. getAbsolutePath () + ":" + f. delete (); // delete file} System. out. println (dir. getAbsolutePath () + ":" + dir. delete (); // delete a folder }}

2. Properties set

API documentation explanation:PropertiesClass represents a persistent property set.PropertiesIt can be saved in a stream or loaded from a stream. In the attribute list, each key and its corresponding value are a string.


Features:

Keys and values in this set are of the string type.

The data in the set can be saved to the stream or obtained from the stream.

This set is usually used to operate configuration files that exist in the form of key-value pairs.

Import java. io. *; import java. util. properties; import java. util. set; public class Main {public static void main (String [] args) throws IOException {PropertiesDemo ();} public static void PropertiesDemo () {// save Properties pro = new Properties (); pro. setProperty ("a", "1"); pro. setProperty ("B", "2"); pro. setProperty ("c", "3"); pro. setProperty ("d", "1"); // modify pro. setProperty ("c", "6"); // Set
   
    
Name = pro. stringPropertyNames (); // stringPropertyNames (): returns the key set in this attribute list. The key and its corresponding value are strings. // if no key with the same name is found in the master attribute list, it also includes different keys in the default attribute list. For (String s: name) {String value = pro. getProperty (s); // getProperty (): Use the specified key to search for properties in this property list. System. out. println (s + ":" + value );}}}
   

3. Combination of Properties set and Stream Object

1. list Method:

Outputs the attribute list to the specified output stream. This method is useful for debugging.

public static void PropertiesDemo() {Properties pro = new Properties();pro.setProperty("a", "1");pro.setProperty("b", "2");pro.setProperty("c", "3");pro.setProperty("d", "1");pro.list(System.out);}

You can call this method to view what is stored in the Properties set at any time.

Similar to System. getProperties ()


2. store Method

This method reflects the persistence in the Properties set and stores the information in the set.

public void store(OutputStream out, String comments)throws IOException
Suitable for use load(InputStream)Method load PropertiesFormat in the table. PropertiesThe attribute list (key and element pair) in the table is written to the output stream.

out-Output stream. comments-Description of the attribute list.

The save method is outdated.

Public static void PropertiesDemo () throws IOException {Properties pro = new Properties (); pro. setProperty ("a", "1"); pro. setProperty ("B", "2"); pro. setProperty ("c", "3"); pro. setProperty ("d", "1"); // store the information in the Properties set persistently in the file. The output stream FileOutputStream fos = new FileOutputStream ("tep.txt") must be associated "); // store the set of data to a file, storepro. store (fos, "name and age"); // Chinese information is not recommended for this method}

3. load Method

load(InputStream inStream)Read the attribute list (key and element pair) in the input stream ).

Public static void PropertiesDemo () throws IOException {// the data in the set comes from the file, instead of the Properties pro = new Properties () We store (); // make sure that the data in the file is key-Value Pair FileInputStream FD = new FileInputStream ("tep.txt"); // use the load method pro. load (FCM); pro. list (System. out );}

Principle

Public static void Myload () throws IOException {Properties pro = new Properties (); BufferedReader br = new BufferedReader (new FileReader ("tep.txt"); String str = null; while (str = br. readLine ())! = Null) {if (str. startsWith ("#") continue; // some configuration information in the file is not a String [] arr = str containing "=. split ("="); // System. out. println (arr [0] + ":" + arr [1]); pro. setProperty (arr [0], arr [1]);} pro. list (System. out); br. close ();}

4. Modify the information in the existing configuration file

1. Read this file

2. Store the key-value information in the text to the set

3. Modify information through a set

4. Store the modified information to a file through a stream

Public static void PropertiesDemo () throws IOException {File file = new File ("tep.txt"); if (! File. isFile () {file. createNewFile ();} FileReader fr = new FileReader ("tep.txt"); // FileWriter fw = new FileWriter (file); if it is placed here, a new file overwrites the file, c = 3 Properties pro = new Properties (); pro. load (fr); // pro. list (System. out); pro. setProperty ("c", "3"); // The output stream object must be associated after modification. do not associate FileWriter fw = new FileWriter (file) above ); // stream can directly operate the File object pro. store (fw, "after change ");}

Iv. Exercises

Obtains the number of times an application has been used. If the number of times exceeds 3, it indicates that the application has been registered. Do not run the application again.

Analysis:

This requires a counter. Each time the program starts the counter into the memory, the number of times is + 1, the program is exited, the counter is closed, and stored to the file.

Because the confidence should be clear, there should be a name and number of times,-> key-value pairs-> Map + IO-> Properties

Public static void PropertiesDemo () throws IOException {File countFile = new File ("conutFile. properties"); // configuration information of key-value pairs (java) if (! CountFile. isFile () countFile. createNewFile (); FileInputStream FCM = new FileInputStream (countFile); Properties pro = new Properties (); pro. load (FS); // obtain the number of times String value = pro from the set by using the key. getProperty ("time"); int count = 0; // defines the counter if (value! = Null) {count = Integer. parseInt (value); // convert to intif (count> = 3) {throw new RuntimeException ("the number of times has arrived. Please register! ") ;}} Count ++; // re-store the changed data. pro. setProperty ("time", count + ""); // modify FileOutputStream fos = new FileOutputStream (countFile); // associate the output stream pro. store (fos, "time is"); // store it to the file fos. close (); FCM. close ();}


During development, this code can be encapsulated into an object, which can be created at runtime.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.