IO stream in Java

Source: Internet
Author: User
Tags processing text

First, Java.io.File class1. He represents a file or directory on disk
2, he has a number of internal packaging methods, you can view this file or directory of some information
Whether the file/directory exists, the file or directory, the size of the file/directory, the modified time, whether it is readable/writable
3, all the input and output related classes, interfaces, etc. are defined under the Java.io package
4. File is a class that can be used by the constructor to create its object, which corresponds to a file (. txt/.avi/.doc/.ppt/.mp3/.jpg) or file directory
5, the path of the file can be an absolute path, or it can be a relative path
6. The File class object is platform Independent
7, the method in file only involves how to create, delete, rename and so on. The file class cannot handle operations that involve the contents of the files and must have an IO stream to handle
8. The object of the file class is usually the parameter of the constructor of the concrete class of Io stream.

Ii. Common methods of File class1. Construction method
Public File (String name)
The construction method of file accepts string, whether it is a valid path or not, later can be judged by some method classes inside file
Public File (String parent,string Child)
Public file (file parent,string child)

2. Access file name:
GetName ()//Get file name
GetPath ()//Get File relative path
Getabsolutefile ()
GetAbsolutePath ()//Get absolute path
GetParent ()//Get Parent Directory
Renameto (File newName)//In the same directory: rename different directories: rename and cut

3, file operation related
CreateNewFile ()//Create File
Delete ()//Remove the file/directory, cannot delete the multilevel directory, if you want to delete the multilevel directory use recursion

4. File detection
exists ()//Determine if the file exists
CanWrite ()//Determine if writable
CanRead ()//determine if readable
Isfile ()//Determine if it is a file
Isdirectory ()//Determine if it is a directory
Ishidden ()//Determine if the file is hidden

5, directory operation related
MkDir ()//Create Directory
Mkdirs ()//Create a multilevel directory
List ()//Get the names of all files and directories under this directory
Listfiles ()//Get file array for all files and directories in this directory
If you only need to get the name, no subsequent actions use list ()
Use ListFile () if you need to follow up on a file or directory

6. Get regular file information
Public long lastmodified ()//Last Modified time
public long Length ()//File length

7. Interface
FilenameFilter (interface): A file filter needs to define a class to implement the interface, and override the Accept () method
Iii. io Stream (directional, linear) 1, basic flow (four abstract classes)
Abstract base-class byte stream with byte stream
Input stream InputStream Reader
Output stream OutputStream Writer
2. Classification of streams
2/1 by Data Flow:
Input stream: Read data from external to application
Output stream: Writes out data from the application to the outside
2/2 per unit of processing data: Byte stream (the text file is handled unexpectedly with a byte stream), character stream (processing text file)
2/3 by role: node flow (directly acting on a file is a node stream), processing flow

3.
Abstract base class node stream buffer stream (can improve file read and write speed)
InputStream FileInputStream Bufferedinputstream
OutputStream FileOutputStream Bufferedoutputstream
Reader FileReader BufferedReader
Writer FileWriter BufferedWriter

4. Byte stream
4/1 methods
4/1/1 FileInputStream (Byte stream)---sub-class of >inputstream
Construction Method:
FileInputStream (String name): Constructs an output pipeline to this file using name as the file path
FileInputStream (file file): Constructs an output pipeline to this file, using file as the path

Member Methods:
public int Read (): reads a data byte from this input stream
public int read (byte[] b): reads up to b.length bytes of data from this input stream into a byte array.
public int read (byte[] b, int off, int len): reads up to len bytes of data from this input stream into a byte array.

4/1/2 FileOutputStream (Byte stream)---sub-class of >outputstream
Construction Method:
FileOutputStream: Creates a file output stream that writes data to files represented by the specified file object.
Public FileOutputStream (File File,boolean append): Creates a file output stream that writes data to a file that is represented by the specified file object. If the second argument is a
True to write bytes to the end of the file, not to the beginning of the file.
Public FileOutputStream (String Filename,boolean append)

Common methods:
public void Write (int b): Output one byte
public void Write (byte[] b): Outputs an array of bytes
public void Write (byte[] b,int off,int len): Outputs a portion of a byte array
4/2 line break
Line breaks under Windows: \ r \ n

5. Conversion stream (character stream)
InputStreamReader OutputStreamWriter
Encoding: String---> Byte array string---> getBytes ()
Decoding: Byte array---> String byte[]---> string (using string construction method)

When we write to the file, if need to display on the screen, it is best to specify the encoding method, to ensure that the encoding and reading when the same encoding method

5/1 OutputStreamWriter (conversion stream, character stream):
Construction Method:
Public OutputStreamWriter (OutputStream out)
Public OutputStreamWriter (OutputStream out,string charsename)

method to write:
public void Write (int n): Write a character
public void Write (char[] cbuf): Writes an array of characters
public void Write (char[] cbuf,int off,int len): writes part of a character array
public void Write (String str): Writes a string
public void Write (string str,int off,int len): Write part of a string
5/2 InputStreamReader (conversion stream, character stream)
Construction Method:
InputStreamReader (InputStream in): Create a inputstreamreader that uses the default character set
InputStreamReader (InputStream in,string charsename): Creates a inputstreamreader using the specified character set
Methods to read:
int read (): reads a single character
int read (char[] cbuf): reads one character array at a time
int read (char[] cbuf,int off,int len);

6. Character Stream
6/1 FileWriter (character stream, basic stream)---sub-class of >outputstreamwriter
Construction Method:
FileWriter (file file): Constructs a FileWriter object based on the given File object.
FileWriter (File File, Boolean append): Constructs a FileWriter object based on the given File object.
FileWriter (FileDescriptor FD): Constructs a FileWriter object associated with a file description typeface.
FileWriter (String filename): Constructs a FileWriter object based on the given file name.
FileWriter (String filename, boolean append): Constructs a FileWriter object based on the given file name and a Boolean value that indicates whether to append the data.

Member method: The member method of the parent class () does not have its own member method

6/2 FileReader (character stream, basic stream)---> InputStreamReader sub-class
Construction Method:
FileReader (File file): Creates a new filereader given the file from which the data is read.
FileReader (FileDescriptor FD): Creates a new filereader given the filedescriptor from which the data is read.
FileReader (String filename): Creates a new filereader given the file name from which the data is read.

7. Standard input/output stream
System.out: return type----InputStream (Byte stream)
System.in: Return type-----outputstream (Byte stream)

8. Data Flow
Data for handling basic data types, byte arrays, string: DataInputStream DataOutputStream

DataOutputStream: The data output stream allows the application to write the basic Java data type to the output stream in an appropriate manner, and the application can then use the input stream to read the data into

Java.lang.Object
|----Java.io.OutputStream
|----Java.io.FilterOutputStream
|----Java.io.DataOutputStream

Member Methods:

void Flush (): Empties this data output stream.
int size (): Returns the current value of the counter written, which is the number of bytes written to this data output stream so far.
void Write (byte[] b, int off, int len): writes the Len byte in the specified byte array from offset off to the underlying output stream.
void write (int b): writes the specified byte (eight low of parameter B) to the underlying output stream.
void Writeboolean (Boolean v): Writes a Boolean value to the underlying output stream as a 1-byte value.
void WriteByte (int v): writes a byte value to the underlying output stream as a 1-byte value.
void Writebytes (string s): writes out the string in byte order to the underlying output stream.
void Writechar (int v): writes a char value to the underlying output stream as a 2-byte value and writes the high byte first.
void WriteChars (string s): writes a string to the underlying output stream in character order.
void writedouble (double v): Use the Doubletolongbits method in the double class to convert the double argument to a long value, and then write the Long value as a 8-byte value to the underlying output stream, first to the high-byte 。
void Writefloat (float v): Use the Floattointbits method in the float class to convert the float parameter to an int value, and then write the int value as a 4-byte value into the underlying output stream, writing the high byte first.
void Writeint (int v): writes an int value to the underlying output stream as a 4-byte value and writes the high byte first.
void Writelong (Long V): writes a Long value to the underlying output stream as a 8-byte value and writes the high byte first.
void Writeshort (int v): Writes a short value to the underlying output stream as a 2-byte value, writing high bytes first.
void writeUTF (String str): Writes a string to the underlying output stream using UTF-8 modified encoding in a machine-independent manner.

DataInputStream:
The data input stream allows the application to read basic Java data types from the underlying input stream in a machine-independent manner. The application can use the data output stream to write data that is later read by the data input stream.

Java.lang.Object
|-----java.io.InputStream
|-----java.io.FilterInputStream
|-----java.io.DataInputStream

DataInputStream is not necessarily secure for multithreaded access. Thread safety is optional and is the responsibility of the user of this class of methods.
Member Methods:

int read (byte[] b): Reads a certain number of bytes from the contained input stream and stores them in buffer array B.
int read (byte[] b, int off, int len): reads up to Len bytes from the included input stream into a byte array.
Boolean Readboolean (): See General contract for the Readboolean method of Datainput.
Byte ReadByte (): See General contract for the ReadByte method of Datainput.
Char ReadChar (): See General contract for the ReadChar method of Datainput.
Double readdouble (): See General contract for the Readdouble method of Datainput.
Float readfloat (): See General contract for the Readfloat method of Datainput.
void Readfully (byte[] b): See General contract for readfully method of Datainput.
void Readfully (byte[] b, int off, int len): See General Conventions for readfully methods of Datainput.
int ReadInt (): See General contract for the ReadInt method of Datainput.
Long Readlong (): See General contract for the Readlong method of Datainput.
Short Readshort (): See General contract for the Readshort method of Datainput.
int Readunsignedbyte (): See General contract for the Readunsignedbyte method of Datainput.
int Readunsignedshort (): See General contract for the Readunsignedshort method of Datainput.
String readUTF (): See General contract for the readUTF method of Datainput.
static string readUTF (Datainput in): Reads a string of Unicode character formatting encoded with the UTF-8 modified version from stream in, and returns this string as String.
int skipbytes (int n): See General contract for the Skipbytes method of Datainput.

9. Object Flow
8/1 is used to store and read the object's processing stream, he can write objects to the data source, you can also restore the object from the data source back
8/2 Serialization (Serialize): Writes a Java object to the IO stream with the ObjectOutputStream class
Deserialization (deserialize): Recovering the Java object from the IO stream with the ObjectInputStream class
8/3 to allow the object of a class to support the serialization mechanism, the class must be serializable
8/4 to implement a serializable class:
8/4/1 class implements Serializable interface
The properties of the 8/4/2 class also implement the Serializable interface
8/4/3 A class that implements the Serializable interface has a static variable that represents the serialized version identifier:
Private static final long serialversionuid;
8/4/4 ObjectOutputStream and ObjectInputStream cannot serialize a transient decorated member variable

10. Randomaccessfile Class (does not belong to any stream)
The 9/1 Randomaccessfile class does not belong to a stream and is a subclass of the object class. Support "Random access" way, the program can jump directly to the file anywhere to read, write files (that is, you can
acts as an input stream and can act as an output stream)
Supports access to only a subset of the contents of a file
You can append content to a file that already exists
The 9/2 Randomaccessfile class object is free to move the record pointer:
Long Getfilepointer (): Gets the current position of the file record pointer
void Seek (Long pos): Position the file record pointer to the POS location
9/3 Constructors
Public randomaccessfile (file file, String mode): Creates a random-access file stream from which to read from and write to (optional), which is specified by the file parameter.
Public Randomaccessfile (string name, String mode): Creates a random-access file stream from which to read and write (optionally), with the specified name.

9/4 Creating a Randomaccessfile class instance requires specifying a mode parameter that specifies the access mode of the Randomaccessfile:
R: Open as read-only
RW: Open for Read and write
RWD: Open for reading and writing; synchronizing file content updates
RWS: Open for reading and writing; synchronizing file content and metadata updates

9/5 member Methods
public long Length (): Returns the length of the file
Read:
public int Read (): reads one byte of data
public int read (byte[] b): reads data from one byte array at a time
public int read (byte[]b, int start,int length): Read part of byte array at a time
Write:
public void Write (byte[] b): reads B.length bytes of data to a file
public void Write (byte[] b, int start, int length):
public void Write (int n): writes the specified byte

11. Memory operation Stream-byte buffer stream
Bytearrayinputstream: Read from memory, no close required
Bytearrayoutputstream: Write to memory, no close required

StringBuffer: Used to cache strings
Bytearrayoutputstream: Used to cache byte[] Arrays

12. Manipulating character arrays
CharArrayReader
Chararraywriter

13. Manipulating strings
StringReader
StringWriter

14. Print Flow
Writer:
|-----printwriter
PrintWriter for automatic refresh and line wrapping
OutputStream
|-----filteroutputstream
|-----printstream

PrintWriter Construction Method:
PrintWriter (file file): Does not have automatic refresh function
PrintWriter (String fielname): Does not have auto refresh feature
PrintWriter (OutputStream out, Boolean AutoFlush): Creates a new printwriter from an existing outputstream.
PrintWriter (Writer out, Boolean AutoFlush): Creates a new printwriter.

If automatic refresh is enabled, this can only be done if one of the methods of println, printf, or format is called.
The Write method does not automatically flush the buffer even if automatic refresh is initiated.

PrintWriter out = new PrintWriter (New FileWriter ("Demo11.txt"), true);
Out.println ("Java");//write () + newLine () + flush (), equivalent to print + line break + Refresh

15. Summary
Input stream: InputStream
Member Methods:
int read ()
int read (byte[] b)
int read (byte[] b, int start,int end)
|-----FileInputStream
|-----filterinputstream
|-----bufferedinputstream

Output stream: OutputStream
Member Methods:
Write (int n)
Write (byte[] b)
Write (byte[] b, int start, int end)
|-----fileoutputstream
|-----filteroutputstream
|-----bufferedoutputstream

Input stream: Reader
Member Methods:
int read ()
int read (char[] b)
int read (char[] b, int start,int end)
|-----inputstreamreader
|-----filereader
|-----BufferedReader
Member Methods:
int read ()
int read (char[] b)
int ReadLine ()
int read (char[] b, int start,int end)

Output stream: Writer
Member Methods:
void write (int c)
void write (char[] ch)
void write (char[] ch, int start, int end)
void write (String str)
void Write (String str, int start,int end)
|-----outputstreamwriter
|-----FileWriter
|-----bufferedwriter

IO stream in 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.