Java--properties collection, object serialization stream and deserialization stream, print stream, Commons-io file tool class

Source: Internet
Author: User
Tags object serialization serialization

first, the properties set

The collection Object properties class, inherits the Hashtable, implements the map interface, can use with the Io object, realizes the data persistent storage.

Characteristics:

    1. The subclasses of the Hashtable , the methods in themap collection can be used.
    2. The collection does not have a generic type. The key values are all strings.
    3. It is a set of properties that can be persisted. Key values can be stored in the collection or stored on a persisted device ( hard disk,U -disk, CD-ROM ) . The source of the key value can also be a persistent device.
    4. With the method of combining with the flow technology.

1. Basic Use
private static void Func () {    //No generic    Properties Pro = new properties ();    Use SetProperty to set key-value pairs, equivalent to the set Pro.setproperty of the map Interface    ("A", "1");    Pro.setproperty ("B", "2");    Pro.setproperty ("C", "3");    System.out.println (PRO);    {a=1, b=2, c=3}    //Gets the value by the key, which is equivalent to the get    String v = pro.getproperty ("C") of the map interface;    System.out.println (v);    Method Stringpropertynames, stores the keys in the collection to the set collection, similar to the method of the map interface keyset    set<string> Set = Pro.stringpropertynames ();    for (String k:set) {        System.out.println (k + "..." +pro.getproperty (K.));}    }
2, read the key value in the file to save to the collection
/* * Properties Collection Unique method load * Load (InputStream in) * Load (reader r) * Pass any byte or character input stream * Stream object read key value pair in file, save to collection */private static void Func () throws IOException {    //Instantiation Properties collection    Properties Pro = new Properties ();    Instantiate the character/byte input stream    FileReader fr = new FileReader ("/home/x54256/desktop/pro.properties");    Read data, save to Propertie collection    Pro.load (FR);    Close file    fr.close ();    Print    System.out.println (pro);    {name=x5456, age=23, [email protected]}}

File format

name=x5456
[Email protected]

3. Save to file
/* * Properties Collection Unique Method Store * Store (OutputStream out) * Store (Writer W) * Receive all bytes or characters of the output stream (requires flush), set the set of key value pairs, write back to the file to save */pri vate static void Func () throws IOException {    Properties Pro = new Properties ();    Pro.setproperty ("name", "x5456");    Pro.setproperty ("Age", "n");    Pro.setproperty ("Email", "[email protected]");    The key-value pair formats the stored-back file, using the collection's method store to pass the character output stream    fileoutputstream fos = new FileOutputStream ("/home/x54256/desktop/1.txt");    Pro.store (FOS, "Save Msg");    Fos.close ();}
second, serialized stream and deserialization stream

The flow of operations used to read an object from a stream ObjectInputStream called a deserialization stream, which is used to write an object to a stream ObjectOutputStream called a serialized stream

    • Features: For manipulating objects. You can write an object to a file, or you can read an object from a file.

Person class

Import Java.io.serializable;public class Person implements Serializable {   //need to Implement interface Serializable    private String Name;    Private/*transient Keyword: block member variable serialization */int age;    class, the serial number is customized, and the compiler does not calculate the serial number (even if the Java code is modified after saving to the file)    private static final long serialversionuid = 1478652478456L;    Tostring,init,get,set method ...}
1. Writing objects to the file
/* * ObjectOutputStream * Construction method: ObjectOutputStream (Outputsteam out) * Pass arbitrary byte output stream * void WriteObject (Object obj) methods for writing out objects */p rivate static void Func () throws IOException {    FileOutputStream fos = new FileOutputStream ("/home/x54256/desktop/2.txt");    ObjectOutputStream oos = new ObjectOutputStream (FOS);    Person p = new person ("x5456", +);    Oos.writeobject (p);    Oos.close ();}
2. Reading objects from a file
/* * ObjectInputStream * Construction method: ObjectInputStream (InputStream in) * Pass arbitrary byte input stream, input stream encapsulates file, must be serialized file * Object ReadObject ()  Read object */private static void Func () throws IOException, classnotfoundexception {    FileInputStream fis = new Fileinpu TStream ("/home/x54256/desktop/2.txt");    Creates a deserialization stream, constructs a method, passes the byte input stream    ObjectInputStream ois = new ObjectInputStream (FIS);    The method that invokes the deserialization stream ReadObject () reads the object    obj = Ois.readobject ();    System.out.println (obj);    Ois.close ();}
third, print flow

The print stream adds the ability to output data so that they can easily print various data value representations.

The print flow is categorized according to the flow:

    • BYTE print stream PrintStream: Constructs a method, receives a file type, receives a string file name, receives a byte output stream outputstream

    • Character Print stream PrintWriter: Construct method, receive file type, receive string file name, receive byte output stream outputstream, receive character output stream writer

Method:

void print (String str): outputs any type of data,

void println (String str): outputs any type of data, automatically writes a line-break operation

Characteristics:

    • 1. This stream is not responsible for data sources, only for data purposes
    • 2. Add features for other output streams
    • 3. Never throw IOException, but may throw other exceptions
1. Writing Files
/* Print stream, write data to the file object's data Purpose * Method print println  Output * Write method walk-through table */public static void function () throws FILENOTFOUNDEXCEP tion{//Files file = new ("C:\\1.txt"); PrintWriter pw = new PrintWriter (file);//string PrintWriter pw = new PrintWriter ("C:\\2.txt");p w.println (100);// 100pw.write (+);//d//byte output stream FileOutputStream fos = new FileOutputStream ("C:\\3.txt"); PrintWriter pw = new PrintWriter (FOS);//character output stream FileWriter fw = new FileWriter ("C:\\4.txt"); PrintWriter pw = new PrintWriter (FW);p w.close ();}
2. Automatic refresh
/* * Print stream for text copy *   read data source  bufferedreader+file Read Text line *   Write Data Purpose printwriter+println automatically refresh */public static void Main ( String[] args) throws Ioexception{bufferedreader BfR = new BufferedReader (New FileReader ("C:\\a.txt")); PrintWriter pw = new PrintWriter (New FileWriter ("D:\\a.txt"), true); String line = null;while (line = Bfr.readline ())!=null) {pw.println (line);} Pw.close (); Bfr.close ();}
iv.. commons-io file Tool class1. Get the file name extension
/* * Filenameutils class method * static string GetExtension (string filename) * Gets the extension of the file name */public static void function () {String Name = Filenameutils.getextension ("C:\\Windows"); SYSTEM.OUT.PRINTLN (name); }
2. Get the file name
/* * Filenameutils class method * static string GetName (string filename) * Get file name */public static void Function_1 () {String name = Fi Lenameutils.getname ("c:\\windows\\"); SYSTEM.OUT.PRINTLN (name);}
3. Judge file suffix
/* * Filenameutils class method * Static Boolean isextension (String filename,string extension) * Determine the filename suffix is not extension */public stat IC void Function_2 () {Boolean b = filenameutils.isextension ("Demo.java", "Java"); System.out.println (b);}
4. Read Text
/* * Fileutils Tool class method * static string readfiletostring (File src) read text, return string */public static void function () throws Ioexcept ion{String s = fileutils.readfiletostring (new File ("C:\\a.txt")); System.out.println (s); }
5. Writing text
/* * Fileutils Tool class method * static void Writestringtofile (file src,string date) * Writes a string directly to the file */public static void Function_1 () Throws Ioexception{fileutils.writestringtofile (New File ("C:\\b.txt"), "I love Java Programming");}
6. Copying Files
/* * Fileutils Tool class method * static void CopyFile (file src,file desc) * Copy file */public static void Function_2 () throws Ioexceptio N{fileutils.copyfile (New file ("C:\\k.jpg"), New file ("D:\\k.jpg"));
7. Copying folders
/* * Fileutils Tool class method * static void Copydirectorytodirectory (File src,file desc) * Copy folder */public static void Function_3 () t Hrows ioexception{fileutils.copydirectorytodirectory (New file ("D:\\demo"), New file ("c:\\"));

Java--properties collection, object serialization stream and deserialization stream, print stream, Commons-io file tool class

Related Article

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.