Java Learning lesson 53rd-io Stream (vii) file object exercises & Properties collection

Source: Internet
Author: User
Tags list of attributes

First, practice

Deep Traverse Folder

Deep traversal is a natural thought of recursion, and recursion naturally reminds me that the underlying algorithm of its implementation is the stack

List all content (including subdirectories) for the specified directory

PS: It is recommended not to traverse the C drive

Import java.io.*;p Ublic class Main {public static void main (string[] args) throws IOException {file Dir = new File ("D:\\ac M training "); Listalldemo (dir,0);} public static void Listalldemo (File dir,int level) throws IOException {System.out.println (level) + folder: "+ Dir.getabsolutepath ()); level++;//to indent//Get all current file/file objects under the specified directory file[] files = dir.listfiles (); for (int i =0;i< files.length;i++) {if (Files[i].isdirectory ()) {Listalldemo (files[i],level);} Else{system.out.println (Level + "file:" +files[i].getabsolutepath ());}}}  public static String Getspace (int.) {//TODO auto-generated method Stubstringbuilder sb = new StringBuilder (); for (int i = 0;i<level;i++) sb.append ("    "); return sb.tostring ();}}

Delete directory

Import java.io.*;p Ublic class Main {public static void main (string[] args) throws IOException {file Dir = new File ("D:\\ac M training 1 ");//dir.delete (dir); If there is content in the file that cannot be deleted from the root directory, you must delete Deletedemo (dir) from the inside; 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 folder}}

second, the properties set

The API documentation explains that Properties the class represents a persistent set of properties. Propertiescan be saved in a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.


Characteristics:

The keys and values in the collection are string types

The data in the collection can be saved to the stream or fetched from the stream

Typically the collection is used to manipulate profiles that exist as 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 () {//storage Properties Pro = new properties ();p Ro.setproperty ("A", "1");p Ro.setproperty ("B" , "2");p Ro.setproperty ("C", "3");p Ro.setproperty ("D", "1");//Modify Pro.setproperty ("C", "6");//Take set<string> name = Pro.stringpropertynames ();//stringpropertynames (): Returns the set of keys in this attribute list, where the key and its corresponding value are strings, or if a key with the same name is not found in the main attribute list, the different keys in the default attribute list are also included. for (string s:name) {String value = Pro.getproperty (s);//getproperty (): Searches for properties in this property list with the specified key. System.out.println (s+ ":" +value);}}}

combination of properties set and stream object

1.list Method:

Outputs a list of attributes to the specified output stream. This method is useful for debugging.

public static void Propertiesdemo () {Properties Pro = new Properties ();p ro.setproperty ("A", "1");p Ro.setproperty ("B", "2 ");p Ro.setproperty (" C "," 3 ");p Ro.setproperty (" D "," 1 ");p ro.list (System.out);}

Call this method at any time to see what the Properties collection stores

and System.getproperties (), almost


2.store method

This method embodies the persistence of the properties set, storing the information in the collection

Store (OutputStream out, String comments) throws IOException
For a suitable use load(InputStream)method is loaded into the PropertiesFormat in the table, set this PropertiesThe list of attributes (key and element pairs) in the table are written to the output stream.

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

And the Save method is obsolete.

public static void Propertiesdemo () throws IOException {Properties Pro = new Properties ();p ro.setproperty ("A", "1");p Ro.s Etproperty ("B", "2");p Ro.setproperty ("C", "3");p Ro.setproperty ("D", "1");//persist the information in the Properties collection to a file, The associated output stream is required fileoutputstream fos = new FileOutputStream ("Tep.txt");//collection data is stored in a file, Storepro.store (FOS, "name and Age");// This method is not recommended to use Chinese information}

3.load method

load(InputStream inStream)The input stream reads the list of attributes (key and element pairs).

public static void Propertiesdemo () throws IOException {//The data in the collection is from the file, not our properties Pro = new properties ();// Note You must ensure that the data in the file is a key-value pair FileInputStream FIS = new FileInputStream ("Tep.txt");//Use the Load Method Pro.load (FIS);p ro.list (System.out);}

Its 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;//because some of the configuration information in the file does not contain "=" string[] arr = str.split ("=");//system.out.println (arr[0]+ ":" +arr[1]);p Ro.setproperty (arr[0], arr[1]);} Pro.list (System.out); Br.close ();}

4. Modify the information in an existing configuration file

1. Read this file

2. Store key-value information in the text in the collection

3. Modifying information by Collection

4. Storing the modified information in a file via 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 you put it here, a new file will be created, overwriting file, and the last saved c= 3Properties Pro = new Properties ();p Ro.load (FR),//pro.list (System.out);p ro.setproperty ("C", "3");//must be changed before the output stream object is associated, Do not associate FileWriter FW = new FileWriter (file) on the above,//stream can manipulate the file object Pro.store (FW, "after Change");}

Iv. Practice

Get the number of uses of an application, more than 3 times, give information about the number of times the usage has been registered, and do not run the program again

Analysis:

This requirement requires a counter, each time the program starts counter into memory, number of times +1, exit program, counter close, store to file.

Because the confidence to be clear, there should be a name and number of,-> key value to->map->map+io Properties

public static void Propertiesdemo () throws Ioexception{file Countfile = new File ("conutfile.properties");// Configuration information for key-value pairs (Java) if (!countfile.isfile ()) countfile.createnewfile (); FileInputStream  fis = new FileInputStream (countfile); Properties Pro = new properties ();p ro.load (FIS);//Gets the number of uses by key from the collection string value = Pro.getproperty ("time"); int count = 0;// Define the counter if (value!=null) {count = Integer.parseint (value);//Convert to Intif (count>=3) {throw new RuntimeException ("The number of uses has been reached, Please register! ");}} count++;//re-stores the changed data Pro.setproperty ("Time", count+ "");//modify FileOutputStream fos = new FileOutputStream (countfile); /associated output stream Pro.store (FOS, "Time is");//Store to File Fos.close (); Fis.close ();}


This code can be encapsulated as an object at the time of development and created at run time.




Java Learning lesson 53rd-io Stream (vii) file object exercises & Properties collection

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.