Java basics: I/O

Source: Internet
Author: User

Java basics: I/O

 

 

I. Overview 1. Definition

The data stored in the variable array and the object is temporary and will be lost after the program ends. To save data permanently, you need to store the data on the disk.

The I/O Technology in java can save data locally to meet the requirements of permanent storage.

2. Stream

A stream is a set of ordered sequences. It can be divided into input streams and output streams based on the operation type.

3. IO. System

Two top-level parent classes of the byte stream:

1, InputStream 2, OutputStream.

 

The two top-level parent classes of the upstream stream:

1, Reader 2, Writer

 

Sub-classes of these systems all use the parent class name as the suffix.

The prefix of the subclass name is the function of this object.

 

 

Ii. Producer stream 1. Origin of consumer stream:

In fact, after a byte stream reads the text byte data, it does not directly operate but first queries the specified encoding table. Obtain the corresponding text.

Perform operations on the text. Put simply: byte stream + encoding table

2. FileReader and FileWriter

 

A. FileWirter writes text

 

FileWriter fw = new FileWriter(d:jinfulin.txt); w.write(dfs);fw.close();

 

B. FileReader reads text

 

FileReader fr = new FileReader (d: jinfulin.txt); int num1 = fr. read (); // read the first character int num2 = fr. read (); // call again to read the second character (Stream feature) System. out. println (char) num1); // print, convert the number to the character System. out. println (char) num2 );

C. Character Buffer

 

 

FileReader fr = new FileReader(demo.txt);/** use read (char []) to read text file data. ** Create a character array first. */Char [] buf = new char [1024]; int len = 0; while (len = fr. read (buf ))! =-1) {// read data bit-1System. out. println (new String (buf, 0, len);} fr. close ();

D. How to store some text in a file on the hard disk?

 


3. the streaming buffer objects-BfferedReader and BufferedWriterBfferedReader and BufferedWriter classes encapsulate the buffer into an object in the same principle.
Example: Copy text from one disk to another

 

3. the basic operations of byte streams are the same as those of byte streams, but byte streams can also operate on other media files.
To put it bluntly, we despise everyone's IQ. Let's take a look at it for example,
Example: Copy mp3

 

Private static void myStreamCopy () throws IOException {// defines the input and output streams and adds the buffer BufferedOutputStream buffo = new BufferedOutputStream (new FileOutputStream (f: copystream )); bufferedInputStream buffi = new BufferedInputStream (new FileInputStream (f: wintitle); // start to copy int ch = 0; while (ch = buffi. read ())! =-1) {buffo. write (ch);} // close the stream buffo. close (); buffi. close ();}


Iv. Conversion stream 1. Source of the conversion stream: a. bridge between the primary stream and the byte stream B. It facilitates operations between the primary stream and the byte stream
2. Application of conversion stream: it is more efficient to convert the data in a byte stream to a bytes stream when it is a character.
InputStreamReader: a bridge between byte and character. Decoding. OutputStreamWriter: a bridge between characters and bytes. Encoding.
3. Example: store text on the console to a file
/** Store the text entered in the console to a file. */Public static void main (String [] args) throws IOException {BufferedReader bufr = new BufferedReader (new InputStreamReader (System. in); BufferedWriter bufw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (F: jinfulin.txt); String line = null; while (line = bufr. readLine ())! = Null) {if (over. equals (line) break; bufw. write (line); System. out. println (line);} bufr. close (); bufw. close ();}


 

V. Basic Rules of stream operations

 

Because there are too many stream objects, I don't know which object to use during development. Understanding the rules helps us to use them.

 

1. Clarify the source and purpose

Source: InputStream Reader

Purpose: OutputStream Writer

 

2. Check whether the data is plain text data.

Source: plain text: Reader

--------- No: InputStream

Objective: To be a plain text Writer

------ No: OutputStream

 

3. Specify the specific device.

Source device:

Hard Disk: File

Keyboard: System. in

Memory: Array

Network: Socket stream

 

Target device:

Hard Disk: File

Console: System. out

Memory: Array

Network: Socket stream

 

4. whether additional functions are required.

1. Whether efficient (buffer zone) is required );

2. Conversion.



Vi. File class 1. Definition: abstract representation of File and directory path names
2. Features: 1) used to encapsulate files or folders into objects
2) convenient operations on file and folder attributes
3) The File class instance is unchangeable. That is to say, once created, the abstract path represented by the File object will never change.
4) The File object can be passed as a parameter to the stream constructor.
3. Initialization:
// You can encapsulate an existing or nonexistent file or directory into a file object. File f1 = new File (c: a.txt); File f2 = new File (c: ,a.txt); File f = new File (c :); File f3 = new File(f,a.txt ); file f4 = new File (c: Your file.separator=abcw.file.separator=a.txt );

4. Common Methods for File objects.
A. Obtain
File file = new File(a.txt); String name = file. getName (); // The obtained file name (a.txt) String absPath = File. getAbsolutePath (); // absolute path. String path = file. getPath (); // relative path long len = file. length (); // file length (size) long time = file. lastModified (); // last modification time

B. Created and deleted
File dir = new File (f: a1jin.txt); boolean B = dir. mkdir (); // create the file dir. mkdirs (); // create a multi-level directory System. out. println (dir. delete (); boolean B = file. createNewFile (); // create a file if it does not exist
C. Judgment
Boolean B = f. exists (); // determines whether the object exists. System. out. println (f. isFile (); // whether the file is System. out. println (f. isDirectory (); // whether the file is a directory

D. Rename
File f1 = new File(c:kkk.mp3);File f2 = new File(d:ccc.mp3);boolean b = f1.renameTo(f2);System.out.println(ccc=+b);

5. Expand application a and obtain the names of files and folders in the current directory, including hidden files.
String [] names = file. list (); if (names = null) // if it is null, return is returned to avoid null pointer exception return; System. out. println (names. length); for (String name: names) {System. out. println (name );}


B. filter all files ending with xx


C. History all files in Depth





D. delete a folder (from the inside out, recursively)

Public class DeleteAll {public static void main (String [] args) {File dir = new File (f: S4); // dir. delete (); // directly delete dirdelete (dir);} private static void dirdelete (File dir) {File [] files = dir. listFiles (); if (files = null) return; for (File file: files) {if (file. isDirectory () {// recursive dirdelete (file) if it is a directory;} // if it is not a directory, delete System. out. println (file. getAbsolutePath () + ---- + file. delete ();} // finally delete the folder in the root directory (this is empty) System. out. println (dir. getAbsolutePath () + ---- + dir. delete ());}}

VII. Properties class


1. Overview

The Properties class does not belong to the class in the IO package, but to the map set. It is also mentioned in the previous section of the map set. However, because the data in the Set uses the stream, it is more appropriate here.

2. features:

1. The keys and values in the set are of the string type.
2. The data in the set can be saved to the stream or retrieved from the stream. This set is usually used to operate configuration files that exist in the form of key-value pairs.

3. Example

Define the function to obtain the number of times an application is running. If the number of times exceeds 5, a prompt is displayed indicating that the number of times of use has reached the registration. Do not run the program.

 

 

Public static void getAppCount () throws IOException {// encapsulate the configuration File into a File object. File confile = new File (count. properties); if (! Confile. exists () {// robust judgment confile. createNewFile ();} // the data in the set comes from a file. // Note: Make sure that the data in the file is a key-value pair. // Use the read stream. FileInputStream FCM = new FileInputStream (confile); Properties prop = new Properties (); prop. load (FCM); // the number of times a file input stream is loaded in the Set // the number of times a key is obtained from the set. String value = prop. getProperty (time); // defines the counter. Record the number of times obtained. Int count = 0; if (value! = Null) {count = Integer. parseInt (value); if (count> = 5) {throw new RuntimeException (the usage has arrived. Please register and pay for it !);}} Count ++; // store the changed number of times in the collection. // Store the data in the collection to a file and use the store method. Prop. setProperty (time, count +); FileOutputStream fos = new FileOutputStream (confile); prop. store (fos, comment .....); fos. close (); FCM. close ();}

 

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.