The IO stream in technical article-java

Source: Internet
Author: User
Tags object serialization

1.File class

When working with files in Java, you can instantiate a file object and assign the path of the files to the Document object using this form.

File F = new file (FilePath);

The basic operations of the file class include:

To determine whether it exists: f.exists ()

Get file name: F.getname ()

Get its absolute path: F.getabsolutepath ()

However, if the view and storage of the file is involved, the input and output stream of IO will be used to operate.

2. Input stream:

There are inputstream classes commonly used.

The following actions are viewed for the TXT class file:

Create an input stream

InputStream input = new FileInputStream (file);

Open a cache area that stores read data

byte[] contentbytes = new byte[input.available ()];

Read all bytes into the cache

for (int i = 0; i < contentbytes.length; i++) {

Contentbytes[i] = (byte) input.read ();

}

Create a string based on a byte array

Content = new String (contentbytes);

Close the stream

Input.close ();

In this way, the contents of the TXT file are stored in a string called content through the input stream and can be used in Java for the next steps.

But the input stream only solves the problem of viewing, if you want to use Java to change the contents of the TXT document, and stored in the original TXT, the output stream will be used.

4. Output stream:

Commonly used have OutputStream class and so on.

To change the contents of the TXT document and store it in the original document as an example, the step reference input stream is as follows:

Create an output stream

OutputStream output = new FileOutputStream (file);

Create an array to store the read string data

byte[] contentbytes = new Byte[content.getbytes (). length];

Storing data stored in a string in a byte array

Contentbytes = Content.replaceall ("\ n", "\ r \ n"). GetBytes ();

Because the Write method in OutputStream can only receive byte type or integer data

Output.write (contentbytes);

Refreshes the output stream and writes out all bytes that are still in the cache

Output.flush ();

Close the stream

Output.close ();

For example, how to make a file finder:

1. Design and create an interface, including the most basic input file path box, search button, display the Found File list box.

2. Create a file class object with the read input file path. Then create a dynamic array of type file, ready to store all files conforming to the object for output. Create an array that will read all the file lists under the F file object into which it is stored.

list<file> files = new arraylist<file> ();

File F = new file (FilePath);
file[] fl = F.listfiles ();

3. The file object is judged if it exists, whether it is a folder or a file, or, if it is a folder, the method FileSearch (String FilePath) that the folder is called again. Save the Read file in the files dynamic array.

for (int i = 0; i < fl.length; i++) {

if (Fl[i].isdirectory ()) {

For (File Child1:filesearch (Fl[i].getabsolutepath ())) {

Files.add (child1);

}

}

}

for (File CHILD1:FL) {

Files.add (child1);

}

4. In the Search Results box, enter the absolute path to the elements in the files dynamic array.

For (File Child:filesearch (FP)) {

if (flag = = False) {

Jtextarea.settext (Child.getabsolutepath ());

}

}

5. Add File name search function:

A new text box is used to enter the file name, compare the resulting file name with the file name listed in FL, and add it to the files dynamic array for display.

if (Fl[i].getname (). Contains (FN) &&!fn.equals ("")) {

Files.add (Fl[i]);

}

6. Add the ability to open a file in the Click Results list:

1. Normal JTextArea does not support the ability to click Back to click Options, so take advantage of the jlist component. The data stored in the jlist is a vector type, so a vector dynamic array is needed to store the resulting files ' dynamic array.

vector<string> list = newvector<string> ();

For (File Child:filesearch (FP)) {

List.addelement (Child.getabsolutepath ());

}

Console.setlistdata (list);

Open selected file: After using the listener to return the resulting object displayed on JList, create a new desktop class to open the selected file. Open by using the open (file name) method.

Desktop op = new Desktop ();

Op.open (filepath);

7. Serialization and deserialization

What is serialization?

When an object is created, it actually creates a storage space in memory for easy storage of information. Object serialization, which is a method of turning an object into a binary data stream, is convenient for saving and transmitting.

When an object wants to be serialized, it needs to inherit the Serialiazable interface.

The Serialiazable interface has no method, and this interface is an identity interface that identifies a certain capability. For example, the serialization identity of a person class:

Import java.io.Serializable;

public class Person implementsserializable{

Private static final long serialversionuid= 1L; Version Declaration

Privatestring name; Declares the Name property, but this property is not serialized

Privateint age; Declaring the Age property

Publicperson (String Name,int Age) {//By constructing content

This.name= name;

This.age= age;

}

Publicstring ToString () {//overwrite ToString () method

Return "Name:" + THIS.name + "; Age:" + this.age;

}

};

This object can then be serialized into a binary Btye stream.

ObjectOutputStream serialized Objects

Incoming output object: ObjectOutputStream (Objectstream o)

Output object: WriteObject (Object o)

public class serdemo01{

publicstatic void Main (String args[]) throws Exception {

Filef = new File ("D:" + file.separator + "test.txt"); Define Save Path

Objectoutputstreamoos = null; Declaring an object output stream

Outputstreamout = new FileOutputStream (f); File output stream

oos= new ObjectOutputStream (out);

Oos.writeobject (Newperson ("Zhang San", 30)); Save Object

Oos.close (); Shut down

}

};

ObjectInputStream deserializing objects

Construct input object: ObjectInputStream (Objectstream o)

Reads an object from a specified location: ReadObject ()

public class serdemo02{

publicstatic void Main (String args[]) throws Exception {

Filef = new File ("address"); Define Save Path

Objectinputstreamois = null; Declaring an object input stream

Inputstreaminput = new FileInputStream (f); File input stream

ois= new ObjectInputStream (input); Instantiating an object input stream

Objectobj = Ois.readobject (); Reading objects

Ois.close (); Shut down

System.out.println (obj);

}

};

Serializing a set of objects is best used to receive an array

public class serdemo05{

publicstatic void Main (String args[]) throws exception{

Personper[] = {New Person ("Zhang San", +), new person ("John Doe", 31),

Newperson ("Harry", 32)};

Ser (per);

Objecto[] = (object[]) dser ();

for (inti=0;i<o.length;i++) {

Personp = (person) o[i];

SYSTEM.OUT.PRINTLN (P);

}

}

publicstatic void Ser (Object obj[]) throws Exception {

Filef = new File ("D:" + file.separator + "test.txt"); Define Save Path

Objectoutputstreamoos = null; Declaring an object output stream

Outputstreamout = new FileOutputStream (f); File output stream

oos= new ObjectOutputStream (out);

Oos.writeobject (obj); Save Object

Oos.close (); Shut down

}

Publicstatic object[] Dser () throws Exception {

Filef = new File ("D:" + file.separator + "test.txt"); Define Save Path

Objectinputstreamois = null; Declaring an object input stream

Inputstreaminput = new FileInputStream (f); File input stream

ois= new ObjectInputStream (input); Instantiating an object input stream

Objectobj[] = (object[]) ois.readobject (); Reading objects

Ois.close (); Shut down

Returnobj;

}

};

The IO stream in technical article-java

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.