Summary of common flow of Javaio flow (I.)

Source: Internet
Author: User

Let's start by outlining what IO is

You imagine and think about it. When you edit a text file, forget ctrl+s and close it is not very painful, when you insert a USB stick on your computer to copy a video from a USB stick into your computer hard drive. Are these data on those devices?

We can think of this kind of data transmission as a kind of data flow, according to the direction of the flow, memory as the basis, divided into inputs and outputs output, that is, the flow of memory is the input stream, output memory output stream

I/O operations in Java are primarily input using the contents of their IO packages, and output operations are typically input called read data output called write-out data

Depending on the direction of the data flow, we can divide it into: input stream and output stream

Input stream: Reads data from other devices into the in-memory stream

Output stream: Writes data out of memory to a stream on another device

Depending on the pattern type of the data can be divided into: byte stream and character stream

BYTE stream: Streams that read and write data in bytes

Character streams: Stream of Read and write data in characters

There are two ancestor times classes in the two major categories of IO streams

In the byte stream:

Input stream: InputStream (byte input stream)

Output stream: OutputStream (byte output stream)

In the character stream:

Input stream: Reader (character input stream)

Output stream: Writer (character output stream)

First, rip the throttle:

In object-oriented thinking, "Everything is Object", and here I also put a set of bytes called "All bytes."

All of the file data is stored in binary numbers as a single byte in the same way when it is transmitted. Therefore, the byte stream can transmit arbitrary file data. So we have to be clear all the times, no matter what stream object is used the underlying transport is always binary data

  byte input stream [InputStream]:

Io. The InputStream abstract class is a superclass of all classes that represent byte input streams and can read byte information into memory. Defines the basic commonality function method of byte input stream

For example:

public void Close (): closes this input stream and frees any system resources associated with this flow

public abstract int Read (): reads the next byte of data from the input stream

public int read (byte[] b): Reads some number of bytes from the input stream and stores them in byte array b

Note: You must call the Close method to free system resources when you have completed the convection operation method

    FileInputStream class:
Io. The FileInputStream class is a file input stream that reads bytes from a file

Construction Method:

FileInputStream (File file): Creates a fileinputstream by opening a connection to the actual file, which is named by the file object files in the filesystem

FileInputStream (String name): Creates a fileinputstream by opening a connection to the actual file named by the pathname name in the file system

When you create a stream object, you must pass in a file path. The path, if not the file, throws FileNotFoundException.

code example:

Create a Stream object using the file object     file File=new file ("A.txt");    FileInputStream fos=new fileinputstream (file);//Create a Stream object    fileinputstream fos=new fileinputstream ("B.txt") using the filename name;

Read byte data:

1. Read bytes: The Read method, each time a byte of data can be read promoted to the int type read to the end of the file, return-1, code example:

//Create a Stream object using the file name firstFileInputStream fis=NewFileInputStream ("Read.txt");//then read the data and return a byte    intRead=Fis.read (); System.out.Println ((Char) read); Read=Fis.read (); System.out.Println ((Char) read); Read=Fis.read (); System.out.println ((Char) read); Read=Fis.read (); SYstem.out.println ((Char) read); //read to end return-1Read=Fis.read (); SYSTEM.OUT.PRINTLN (read);//Finally, remember to close the resourcefis.close ();//------------------------------------------------------------------------------------//use loops to read and write//first create a Stream object with a file nameFileInputStream fis=NewFileInputStream ("Read.txt"); //define variables, save data        intb; //Loop Read         while((B=fis.read ())!=-1) {System.out.println (Charb)); }    //Close ResourceFis.close ();

Note: Read bytes are automatically promoted to type int, and system resources must be freed after the stream operation to call the Close method

2. Read with byte array: Read (byte[] b), each time you read the length of B to the array, return the number of valid bytes read to the end, return 1

code example:

Create a Stream object using the file name    fileinputstream fis=new fileinputstream ("D:\\aaa.txt");//file with ABCDE    //define variable as valid number    int len ;    Defines a byte array as a container for byte-loaded data    byte[] b=new byte[2];    Loop read    while ((Len=fis.read (b))!=-1) {        //after each read, print the array programming string        //system.out.println (new string (b));
Len number of valid bytes per read
System.out.println (New String (B,0,len)); } Close Resource fis.close ();
If normal execution results in a single one , you get a valid byte by Len
Using array reads to read multiple bytes at a time reduces the number of system IO operations to improve read and write efficiency

byte output stream [OutputStream]:

Io. The OutputStream abstract class is a superclass of all classes that represent the byte output stream, and writes the known byte information to the destination. He defines the basic commonality function method of byte output stream

For example:

public void Close (): closes this output stream and frees any system resources associated with this stream

public void Flush (): refreshes this output stream and forces any buffered output bytes to be written out

public void Write (byte[] b): Writes the b.length byte from the specified byte array to this output stream

public void Write (byte[] b,int off,int len): Writes Len bytes from the specified byte array, starting from offset off to output to this output stream

public abstract void Write (int b): The specified byte output stream

Note: You must call the Close method to release system resources when you complete the operation of the stream

FileOutputStream class:

There are many subclasses of OutputStream, the simplest of which is the FileOutputStream class, which is a file output stream for writing data out to a file

Construction Method:

Public FileOutputStream: Create a file output stream to write files represented by the specified file object

Public FileOutputStream (String name): Creates a file output stream to write to a file with the specified name

When you create a stream object you must pass in a file path under that path if no this file will create the file if there is a file that will empty this file's data

code example:

Create a Stream object using the file object    file File=new file ("A.txt");    FileOutputStream fos=new fileoutputstream (file);    Create a Stream object using the file name    fileoutputstream fosr=new fileoutputstream ("B.txt");

Write out byte data:

1. Write-out byte: write (int b) method can write one byte of data at a time

Create a Stream object using the file name    fileoutputstream fos=new fileoutputstream ("Aaa.txt");    Write out the data    Fos.write (97);//write the first byte    fos.write (98);//write the second byte    fos.write (99);//write a third byte        //Close the resource    Fos.close ();

Note: Although the parameter is of type int four bytes but only one byte of information is left to write out

2. Write out the byte array: Write (byte[] b) Each time you can write the data in the array

    

Create a Stream object using the file name    fileoutputstream fos=new fileoutputstream ("Fos.txt");    string conversion to byte array    byte[] b= "Dark Horse Programmer". GetBytes ();    Writes out byte array data     Fos.write (b);    Close Resource    fos.close ();

3. Write the specified length byte array: Write (byte[] b,int off,int len) Each time you write out a Len byte from the off index, the code example:

  

Create a Stream object using the file name    fileoutputstream fos=new fileoutputstream ("Fos.txt");    Convert string to byte array    byte[] b= "ABCDE". GetBytes ();    Write from index 2 start 2 byte index 2 o'clock C two bytes that is CD    fos.write (b,2,2);    Close Resource    fos.close ();

Data Append and Resume

Each time the program runs, the output stream object will empty the data in the destination file.

Public FileOutputStream (File File,boolean append): Creates a file output stream to write to the file represented by the specified file object.

Public FileOutputStream (String Name,boolean Append): Creates a file output stream to write to a file with the specified name

Both of these constructor methods, which need to pass in a Boolean to indicate that the append data is false, means that the original data code example is emptied:

  

Create a Stream object using the file name    fileoutputstream fos=new fileoutputstream ("Aaa.txt", true);    Convert string to byte array    byte[] b= "ABCDE". GetBytes ();    Write out starting at index 2, 2 characters index 2 is c two bytes that is CD    Fos.write (b);    Close index    Fos.clos e ();

Output line break

The newline symbol in Windows system is \ r \ n. code example:

Create a Stream object using the file name    fileoutputstream fos=new fileoutputstream ("Aaa.txt");    Define byte array    byte[] words={97,98,99,100,110};    Iterate over array for    (int i = 0; i < words.length; i++) {        //write out a byte        fos.write (Words[i]);        Write a newline newline symbol to the array to write        out fos.write ("\ r \ n". GetBytes ());    }    Close Resource    fos.close ();

Character Stream

  Character input stream "Reader"

Io. The reader abstract class is a superclass that represents all classes used to read a stream of characters, and can read character information into memory. The basic common method of it

public void Close (): Closes this stream and frees any system resources associated with this stream

public int Read (): reads a character from the input stream

public int read (char[] cbuf): reads some characters from the input stream and stores them in the character array cbuf

  FileReader class:

Io. The FileReader class is a convenient class construct that reads character files by using the system default character encoding and default byte buffer, the so-called system default character encoding: Windows default Chinese encoding when GBK the default byte buffer when a byte array is used to temporarily store byte data

    Construction Method:

FileReader (File file): Create a new FileReader given the File object to read

Filerader (String fileName): Create a new filereader given the name of the file to read

  

Create a Stream object using the file name FileReader fr=new filerader ("D:\\bb.txt");  Read character data int b=fr.reader ();  Use a character array to read char[] c=new char[2]; System.out.println (New String (c));

  

 Character output stream "Writer":

Io. Writer Abstract class is a superclass that represents all classes used to write out a character stream, and writes out the specified character information to the destination. It contains the basic common methods of the output stream:

void write (int c): writes a single character

void Write (char[] c): Write character array

abstract void Write (char[] c,int off,int len): Writes the starting index of a part of the character array off array, the number of characters Len writes

void write (String str): Write String

void Write (string str,int off, int len): Number of start index len of the off array to write a portion of the string

void Flush (): Refreshes the left buffer

void Close (): Closes this stream (also automatically refreshes when turned off

   FileWriter class:

Io. The FileWriter class is a convenient class construct that writes characters to a file by using the system default character encoding and default byte buffers

Construction Method:

FileWriter (File file): Create a new FileWriter given the File object to read

FileWriter (String fileName): Create a new FileWriter given the name of the file to read

    

Create a stay object with the file name FileWriter fw=new FileWriter ("D:\\aaa.txt");    Write out the character fw.write (97);    Close and Refresh Fw.write (98);    Fw.flush ();    Fw.write (99);    Fw.close ();    Other uses of write Fw.write ("hehe");    Fw.write (new char[])//continue to write with newline FileWriter fw=new FileWriter ("Aaa.txt", true); Fw.write ("\ r \ n");

Make a mouth use exception handling IO error write only the new JDK7 feature, because this is a common notation.

Try (FileInputStream fis=new fileinputstream (filepath);
FileOutputStream fos=new FileOutputStream (filePath1)) { byte[] buffer=new byte[1024]; while (true) { int temp=fis.read (buffer,0,buffer.length); if (temp==-1) {break ; } else { fos.write (buffer,0,temp);}}} catch (IOException e) { System.out.println (e); }

When it comes to storing data, I have to mention Priperties class

 attribute Set "Properties" inheritance and Hashtable are used to represent a persistent set of properties This class uses a key-value structure to store data, each key and its corresponding value, as a string, because it inherits the word hash

  Construction Method :

Public properties (): Create an empty property list

  Basic Storage methods:

Public Object setProperty (String key,string value): Save a pair of properties

public string GetProperty (string key): Searches for property values using the key specified in this property list

Public Set<string>stringpropertynames (): The collection of names of all keys

code example:

Create property Set object Properties   properties=new properties ();   Add key value to element   Properties.setproperty ("Xiaoming", "+");   Properties.setproperty ("Small Square", "the");   Properties.setproperty ("Floret", "the");   Print property Set Object   System.out.println (properties);   Get the property value by key   System.out.println (Properties.getproperty ("Xiao Ming"));   System.out.println (Properties.getproperty ("Small square"));   System.out.println (Properties.getproperty ("Floret"));   Traversal property set Gets the collection of all keys   set<string> strings=properties.stringpropertynames ();   Print key value pair for   (string string:strings) {      System.out.println (strings+ "--" +properties.getproperty (string));   }

Flow-related methods

public void Load (InputStream instream): Reads a key-value pair from a byte input stream

code example:

Create property Set Object        properties  pro=new properties ();        Load the text information into the property set        pro.load (New FileInputStream ("D:\\aaa.txt"));        Traverse Set Merge Print        set<string>strings =pro.stringpropertynames ();        for (string string:strings) {            System.out.println (string+ "--" +pro.getproperty (string));        }

  

Summary of common flow of Javaio flow (I.)

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.