Java-io Flow Chapter

Source: Internet
Author: User
Tags parent directory

1. Java.io.File class

The file class represents system files (files and directories), and files and directories on disk are represented in Java programs by an instance of the file class.

Common construction Methods: File (String pathname); File (file parent, String child); File (String parent,string Child)

Creates a file object with pathname as the path, and if pathname is a relative path, it is relative to the Java

The path in System Properties User.dir (that is, the directory in which the current bytecode runs).

A common property of the file class: public static final String separator

The path delimiter for the current system is stored. The field value is "/" in Unix and "\ \" in Windows.

Role: The implementation of cross-platform, with this expression delimiter can not worry about, different system representation.

Common methods for 2.File classes

File read and Write properties:

Boolean canexecute ();//test whether the application is able to execute the file.

Boolean canRead (); Whether it can be read.

Boolean canWrite (); Whether you can modify

Judge:

Boolean equals (Object obj); Tests whether this abstract pathname is equal to a given object

Boolean exists (); Test whether this file or directory already exists

Boolean isdirectory ();//Determine if it is a directory

Boolean isfile (); Determine if it is a file

Boolean Ishidden (); Determine if it is a hidden file

Get:

Long length (); Returns the length of the file, in bytes

Long LastModified (); Returns the last time the file was modified

File getabsolutefile ();//Returns the absolute pathname form for this abstract path name.

String GetAbsolutePath (); Returns the absolute pathname string for this abstract path name

String getName ();//Gets the name of the file name or the last directory of the abstract path.

String getParent ();//Returns the path string of the parent directory, or NULL if the path does not specify a parent directory

String GetPath (); Converts this abstract path name to a pathname string.

Operation on the file:

Boolean createnewfile (); Create a new empty file when it does not exist

Boolean delete (); Delete this file, if it is a directory, must be empty to delete, and delete the bottom of the directory

Boolean mkdir ();//Create the directory specified by this abstract path name

Boolean mkdirs (); Create this directory, including all the parent directories that are required but not present.

Boolean Renameto (file dest);//rename this file

Browse files and subdirectories in the directory

String [] List ();//Returns an array of file names and directory names for this directory

File[] Listfiles ();//Returns an array of file instances of files and directories in this directory.

File[] Listfiles (filenamefilter filter);//returns the files and directories in this directory that meet the specified filter

Java.io.FilenameFilter Interface: A class instance that implements this interface can be used to filter file names.

3. File creation Steps

1. File or directory.

2. File-A. First judgment, f.exists (); B. Creation, F.createnewfile (); The file can only be created under a path that already exists.

Directory-A. First judge, F.exists (); B. Create-f.mkdir ();//When only the last directory on the path does not exist

|-f.mkdirs ();//When multiple directories are not present on the path

4.Java I/O principle

A data stream (stream) is a channel that communicates data.

The input of the Java program to the data, and the output operation is carried out in a "stream" manner. A variety of "stream" classes are available in the JDK to get different kinds of data

5. Classification of streams

5.1 Direction of Flow:

    • Input stream: The stream from which the program can read data
    • Output stream: A stream to which a program can write data

5.1 Data transmission Units

    • BYTE stream: The flow of data that is transmitted in bytes.
    • Character Stream: A stream that transmits data in characters.

5.3 Features

    • Node Flow: A stream used to directly manipulate a target device
    • Processing flow: Is the connection and encapsulation of an existing stream, through the processing of the data to provide a more powerful, flexible read and write function.

6. Types of Streams

All stream classes are located in the Java.io package, each inheriting from the following four abstract stream classes

Input stream------InputStream (Byte stream)------Reader (character stream)

Output stream------OutputStream (Byte stream)------Writer (character stream)

7.InputStream Abstract class

Streams that inherit inputstream are used to enter data into the program, and the data is in one byte.

InputStream |----fileinputstream (node stream) |----sequenceinputstream (process Flow)

|----PipedInputStream |----objectinputstream

|----StringBufferInputStream |----FilterInputStream |----datainputstream

|----Bytearrayinputstream |----bufferdinputstream

Basic methods of 7.1 inputstream (all throws IOException)

    • abstract int read ();//The integer representation of the next byte of the data being read from the input stream (asii code value), at which end is returned-1
    • int read (byte [] b);//reads B.length bytes of data from the input stream into B, returning the total number of bytes actually read.
    • int read (byte [] b,int off,int len); Reads len bytes of data, written from off.
    • void Close (); Closes this input stream and frees all system resources associated with this stream
    • Long Skip (long n); Skips and discards the N bytes of data in this input stream, returning the number of bytes dropped
    • int available (); Returns the estimated number of bytes (or skipped) that a method can (not be blocked) to read (or skip) at the end of this input and returns 0

8.OutputStream Abstract class

The stream that inherits OutputStream is the program used to output data outward, and the data unit is one byte

OutputStream |----fileoutputstream (node stream) |----objectoutputstream (process Flow)

|----PipedOutputStream |----Filteroutputstream |----dataoutputstream

|----Bytearrayoutputstream |----bufferedoutputstream

8.1 OutputStream Basic methods (both throws IOException)

    • abstract void Write (int b);//writes the specified byte (corresponding asii code) to this output stream
    • void Write (Byte []b);//writes B.length bytes to this output stream.
    • void Write (Byte []b,int off,int len);//start from off, write Len bytes
    • void Flush ();//flushes the output stream and forces all buffered output bytes to be written out.
    • void Close (); Close this stream and release the related resources

9. Reader Abstract class

The stream that inherits reader is the input data to the program, the data unit is one character (16 bits)

Reader |----pipedreader (node stream) |----BufferedReader |----linenumberreader (process Flow)

|----StringReader (node stream) |----FilterReader |----pushbackreader (process Flow)

|----chararrayreader (node stream) |----inputstreamreader (processing Flow) |----filereader (node stream)

Basic methods of 9.1 Reader

    • int read ();//Read single character, return as Integer value, reach end return-1
    • int read (char[] c);//read into the char array, returning the actual number of characters read.
    • int read (char [] c,int off,int len);//Read Len characters and write from off
    • void close ();//close stream and release related resources
    • Long Skip (long n);//Skip N characters

Writer Abstract class

The stream that inherits writer is the program used to output data outward, and the data unit is one character (16 bits).

Writer |----pipedwriter (node stream) |----bufferedwriter (process Flow)

|----Chararraywriter |----printwriter (process Flow)

|----StringWriter |----outputstreamwriter (processing Flow) |----FileWriter (node stream)

The basic method of 10.1 Writer

    • void writer (int c);//write single character
    • void writer (char [] c);//write character array
    • void writer (char [] c,int off, int len);//write Len characters
    • void writer (string str);//write String
    • void writer (string str,int off,int len);//write a part of a string
    • void Flush ();//forcing the buffered data to be written to the destination
    • void close ();//close the stream, but refresh it first

11. Node Stream type

Attention:

Standard input/output stream

The default input device is the keyboard, and the output device is the monitor.

The type of system.in is InputStream.

The type of System.out is a subclass of PrintStream that is a subclass of OutputStream Filteroutputstream

12. File stream

File streams are primarily used for manipulating files

The JDK offers 4 types of:

    • FileInputStream inherited from InputStream
    • FileOutputStream inherited from OutputStream
    • FileReader inherits from Reader's InputStreamReader
    • FileWriter inherits from writer's OutputStreamWriter

13. Conversion Flow

In the IO package, there is a byte stream and a character stream, but there is also the conversion stream: byte stream-character stream.

Convert stream to convert between byte stream and character stream

The JDK provides two kinds of conversion streams

InputStreamReader: is a subclass of reader that converts the input stream of bytes into a stream of characters, which will be a byte stream

The input object becomes the input object of a character stream.

OutputStreamWriter: Is the subclass of writer, the output of the character stream into a byte stream, a character stream will be

The output object becomes the output object of the byte stream.

14. Memory Stream

Memory streams are primarily used to manipulate memory

Bytearrayinputstream and Bytearrayoutputstream

The input and output can be from a file, or it can be set on top of memory.

Bytearrayinputstream is mostly done to read the content from memory into the program, Bytearrayoutputstream

The primary is to write data to memory.

15. Buffer Stream

The buffer stream is based on the corresponding node stream, which provides buffering function to read and write data, improves the efficiency of reading and writing, and adds some new methods.

The JDK provides four buffer streams:

Bufferedinputstream can be packaged with any InputStream stream.

Bufferedoutputstream can be packaged with any outputstream stream.

BufferedReader can wrap any reader stream: the new ReadLine () method is used to read one line of string at a time (' \ r ' or ' \ n ' ends at a line)

BufferedWriter can wrap any writer stream: a new newline () method is added to write a row delimiter.

Note: For buffered output streams, it is a good idea to flush the data in the cache with the flush () method before closing this stream.

Closes the processing stream and automatically closes all the underlying streams that are wrapped

16. Data Flow

DataInputStream, DataOutputStream belongs to the processing stream. Provides a way to access the machine-independent Java basic data types

Construction Method: node flow with a one-byte parameter

DataInputStream (InputStream in);

DataOutputStream (OutputStream out);

17. Print Flow

Both PrintStream and printwriter are output streams, respectively, for bytes and characters.

Both: Both provide a series of overloaded print and println methods to output various types of data

Both: The output operation does not throw an exception, System.out. is an example of PrintStream

18. Object Flow

The ObjectOutputStream and ObjectInputStream classes provided by the JDK are processing streams for storing and reading basic data types or objects

    • The mechanism for saving basic data types or objects with the ObjectOutputStream class is called serialization
    • The mechanism for reading basic data types or objects with the ObjectInputStream class is called deserialization

Note: Classes that can be serialized as corresponding must implement java.io.Serializable this identity interface

19. Pipe Flow (Piped)

PipedInputStream (Pipedreader), PipedOutputStream (PipedWriter) suitable for communication between threads

With the pipeline flow class, you can implement loosely coupled communication between the various program modules without having to modify the inside of the module. Achieve the characteristics of "strong cohesion, weak coupling".

20.RandomAccessFile class

The main function is to complete the random read function, can read the content of the specified location

Open mode of File:
?“ R "opens in read-only mode. Any write method that invokes the result object will cause the IOException to be thrown.
?“ RW "opens for read and write. If the file does not already exist, try to create the file.
?“ RWS "opens for read and write, and for" RW ", also requires that each update to the contents or metadata of the file be synchronously written to the underlying storage device.
?" RWD "Open for Read and write, and for" RW ", also requires that each update to the file contents be synchronously written to the underlying storage device.

21. Coding Problem Solving method

Law One: java.lang.string

//law one: XX code-->new String (byte[]b,charset xx)-->stirng.getbytes (Charset YY)-->YY encoded public static void Method_1 () throws Exception {FileInputStream fis=new fileinputstream ("f:\          \test\\test.txt ");         File F=new file ("F:\\test\\copy-test2.txt");         if (!f.exists ()) f.createnewfile ();                  FileOutputStream fos=new FileOutputStream (f);         byte [] b=new byte[10];         int len=0; while ((Len=fis.read (b))!=-1) {//idea: GB2312 to UTF-8, must pass an intermediate encoding medium, here is a string//convert byte array to Stri                  Ng (whose encoding is the same as the operating system)//GBK string to another encoded byte array string S=new string (B,0,len, "GB2312");          B=s.getbytes ("UTF-8");         Fos.write (B,0,len); Note: This is wrong because the length of the byte array after transcoding has changed, not the original length of the byte array fos.write (b);         } if (Fos!=null) fos.close ();    if (fis!=null) fis.close (); }

Law II: java.io.inputstreamreader/outputstreamwriter: Bridge Conversion

Law II (recommended): "IO Stream" XX code-->inputstreamreader (file, "XX")--->outputstreamwriter (file, "yy")-->yy encoded public    static void Method_2 () throws Exception    {         fileinputstream fis=new fileinputstream ("F:\\test\\test.txt");          File F=new file ("F:\\test\\copy-test.txt");         if (!f.exists ())             f.createnewfile ();         FileOutputStream fos=new FileOutputStream (f);         Io transfer         inputstreamreader isr=new inputstreamreader (FIS, "GB2312");         OutputStreamWriter osw=new outputstreamwriter (FOS, "UTF-8");         READ:         Char [] cs=new char[1024];         int len=0;         while ((Len=isr.read (CS))!=-1)        {             osw.write (Cs,0,len);         }         Close Flow        osw.flush ();        Osw.close ();        Isr.close ();    }

Method Three: Java.nio.Charset

Summarize:

Idea: 1. Clear source, destination is what, memory, hard disk files.

Keyboard (system.in belongs to InputStream), console (System.out. belongs to Printstrem,outputstream)

2. Flow, is input, or output.

3. The data type of the operation, whether it is a character or a byte

4. What is suitable for the packaging flow (processing flow) suitable for the topic requirements, is the buffer stream, data flow, memory flow, conversion stream.

Java-io Flow Chapter

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.