An analysis of Io flow in Java

Source: Internet
Author: User

1.java.io under the Bag
File class : An object of this class in a Java program that corresponds to a file on the hard disk or to a resource in the network.
File File1 = new file ("D:\\io\\helloworld.txt");
File File2 = new file ("D:\\io\\io1");
>1.file can represent either a file (. doc. xls. mp3. avi. jpg. dat) or a file directory!
The objects of the >2.file class are platform-independent.
The >3.file class is for files or file directories, only new, deleted, renamed, upper-level directories, and so on. If you are involved in accessing the contents of a file
is powerless and can only be implemented using the corresponding input and output streams provided by the IO stream.
>4. The object of the file class is often passed as a parameter to the constructor of the corresponding input and output stream!

Basic common methods under the file class:

Boolean exists (); Determine if the file exists

Boolean mkdir (); Create folder path (only one layer)

Directory

Boolean mkdirs (); Create folder path (can be over-layered)

Creatnewfile Creating a file

Delete Deletes a file

Renameto (file file) rename

GetName Get file name

GetPath Get file path

Length of File

Isdirectory: Judging is not a directory

Isfile is not a file

File[] Listfiles get all files and directories under the current folder

Import Java.io.file;public class Testfile {public static void main (string[] args) {file Filet=new file ("e:\\ Baiduyundownload ");/*boolean b=filet.isdirectory (); System.out.println (b); File[] Fil=filet.listfiles (); for (File F:fil) {System.out.println (f);} */testfile.printf (filet,1);} public static void printf (file F,int len) {if (f.exists ()) {//file exists file[] File=f.listfiles ();//create file array for (filename fi:file) { Iterate through the array if (Fi.isdirectory ()) {//If the array continues to enter the method and prints out the folder name Kongge (len); System.out.println (Fi.getname ()); printf (fi,len+1); }else{Kongge (len); System.out.println (Fi.getname ()); }}}}public static void Kongge (int len) {//to the front of the folder with a space for (int i=0;i<len;i++) {System.out.print ("  ");}}

IO Stream Classification:

 

3.IO Stream Partitioning
1) varies by flow direction: input stream output stream ( station at program Angle )
2) varies by unit of data in the stream: byte stream character stream (plain text files use a stream of characters, in addition to byte streams )
3) different from the role of the stream: Node stream processing flow (stream is directly acting on the file is the node stream (4), in addition to the processing flow)

4. Focus on
* Abstract base class (InputStream, Ourputstream, Reader, Writer)   node stream (file stream) buffer stream (one of the processing flows that can improve the efficiency of file operations)
* inputstreamfileinputstream (int read (byte[] b)) Bufferedinputstream (int read (byte[] b))
Span style= "COLOR: #888888" > * Outputstreamfileoutputstream (void write (B,0,len)) Bufferedoutputstream (Flush ()) (void Write (B,0,len))
* Reader FileReader (int read (char[] c)) BufferedReader ( ReadLine ()) (int read (char[] c)) or string ReadLine ()
* Writerfilewriter (void Write (C,0,len)) BufferedWriter (Flush ()) (void Write (C,0,len) or void write (String str))
Note: 1. read a file from the hard disk, Requires this file to exist. If not present, report the exception of FileNotFoundException
2. Output a file from the program to the hard disk, this file can not exist. If it does not exist, create an implementation output. If present, overwrites the existing file with
3. When really developing, use buffer streams instead of node streams
4. The main end is to close the corresponding stream. Close the output stream first, and then close the input stream. Put this action in the finally

package day31;import java.io.bufferedreader;import java.io.BufferedWriter; Import Java.io.file;import java.io.filenotfoundexception;import java.io.filereader;import java.io.FileWriter; Import Java.io.ioexception;import Java.io.reader;import Java.io.writer;public class Iotext {public static void main ( String[] (args) {file Fi=new file ("c:\\users\\gaofangquan\\desktop\\ new folder \ \ new text document. txt"); File Fi1=new file ("c:\\users\\gaofangquan\\desktop\\ new folder \ \ New text document (3). txt"); try {Reader r=new FileReader (FI); Writer w=new FileWriter (FI1); BufferedReader br=new BufferedReader (R); BufferedWriter bw=new BufferedWriter (w);//char[] C=new char[5]; String str=null; @SuppressWarnings ("unused") int len=0;//while ((Len=br.read (c))!=-1) {//can receive while using a character array (str=    Br.readline ())!=null) {bw.write (str);    Bw.newline (); Bw.flush ();//Refresh}bw.close (); Br.close ();}   catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} }}

  

5. Other flows
1. Convert stream: Implements conversion between byte stream and character stream
InputStreamReader: Input, implement the conversion of byte stream to character streams, improve the efficiency of operation (if the data is a text file) ===> decode: Byte array---> String
OutputStreamWriter: The conversion of the character stream to the byte-stream is implemented when output. ===> encoding: string----> Byte array
Example: Entering a string from the keyboard requires that the entire line of the read string be converted to an uppercase output. Then proceed with the input operation until you exit the program when you enter "E" or "exit".

Package Day31;import Java.io.bufferedreader;import Java.io.bufferedwriter;import java.io.filewriter;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.writer;public class Zhuanhuan {public static void Main (string[] args) {InputStreamReader isr=new inputstreamreader (system.in); BufferedReader br=new BufferedReader (ISR); try {Writer w=new FileWriter ("c:\\users\\gaofangquan\\desktop\\ new folder \ \ New text Document (5). txt "); BufferedWriter bw=new BufferedWriter (w); String S=null;while ((S=br.readline ())!=null) {if (S.equalsignorecase ("Exit")) {break;} Bw.write (s); Bw.newline ();//newline Bw.flush ();} Bw.close (); Br.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

  

2. Standard input and output stream
System.in:The "standard" input stream: Entering data from the keyboard
System.out:The "standard" output stream: outputting data from the monitor

3. Print streams (all output streams) printstream (processing bytes) PrintWriter (processing characters)
You can use System.setout (PrintStream p) to reset the position of the output.
PrintStream p = new PrintStream (New FileOutputStream ("Hello.txt"), true);

Package Print;import Java.io.bufferedreader;import Java.io.filenotfoundexception;import java.io.FileReader;import Java.io.ioexception;import Java.io.printstream;import Java.io.reader;public class TestPrintStream2 {public static void Main (string[] args) {String fileName = "c:\\users\\gaofangquan\\desktop\\ new folder \ \ New text document (6). txt"; list (FileName, System.out);} private static void list (String fileName, PrintStream PS) {try {Reader r=new filereader (filename); BufferedReader br = new BufferedReader (r); String s = null;while ((s = br.readline ()) = null) {//System.out.println ();p s.println (s);//equals System.out.println ();} Br.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {ps.println ("Cannot read file!"); E.printstacktrace ();}}}

  


4. Data streams (processing basic data types, string classes, byte arrays)
DataInputStream DataOutputStream

Package Data;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.datainputstream;import Java.io.dataoutputstream;import Java.io.ioexception;public class TestDataStream { public static void Main (string[] args) {Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();D ataoutputstream dos = NE W DataOutputStream (BAOs); try {dos.writedouble (Math.random ());d Os.writeboolean (true); Bytearrayinputstream Bais = new Bytearrayinputstream (Baos.tobytearray ()); System.out.println (Bais.available ());D atainputstream dis = new DataInputStream (Bais);/* First Out---queue * advanced---stack */ System.out.println (Dis.readboolean ()); System.out.println (Dis.readdouble ());//Two data occupy different space must comply with the advanced post-out dos.close ();d is.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}

  


5. Object flow (used to work with objects)
> Serialization of Objects: Allows the translation of in-memory Java objects into a platform-independent binary stream, allowing this binary stream to persist on disk,
or transfer this binary stream to another network node over the network. When other programs acquire this binary stream, they can revert to the original Java object
ObjectInputStream (Object ReadObject ();) ObjectOutputStream (void WriteObject ( Object obj)
How to create a stream of objects: objectoutputstream oos = new ObjectOutputStream (New FileOutputStream ("Person.txt") );
ObjectInputStream ois = new ObjectInputStream (new FileInputStream (New File ("Person.txt")); The

object of the serialization mechanism corresponds to the requirements of the class: ① requires the class to implement the Serializable interface ② also requires that all properties of the class must also implement the Serializable interface
③ requires that a sequence version number be provided to the class: private static Final long Serialversionuid;
The ④ property is declared static or transient and cannot be serialized

Package Object;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.FileOutputStream ; Import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.io.serializable;public class Testobjectstream {public static void main (string[] args) {try {Test t = new Test (); T.I + = 5; FileOutputStream fos = new FileOutputStream ("c:\\users\\gaofangquan\\desktop\\ new folder \ \ New text document (6). txt"); O Bjectoutputstream Oos = new ObjectOutputStream (FOS); Oos.writeobject (t); Oos.flush (); Oos.close (); FileInputStream fis = new FileInputStream ("c:\\users\\gaofangquan\\desktop\\ new folder \ \ New text document (6). txt"); O Bjectinputstream ois = new ObjectInputStream (FIS); Test t_read = (test) ois.readobject (); System.out.println (T_read); Ois.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (ClassNotFoundException e) {e.printstacktrace ();} catch ( IOException e) {e.printstacktrace ();}}} serializable---labeled interface, there is no actual method, just to indicate that the class can be serialized class Test implements Serializable {private static final long serialversionuid = 1L; String name = "Hanqi"; int i = 3;int J = 15;transient//Transparent, indicating that this property does not consider double d = 12.345 when writing to the stream; @Overridepublic String ToS Tring () {return "Test [name=" + name + ", i=" + i + ", j=" + j + ", d=" + D + "]";}}

  

6. Random Access file stream: Randomaccessfile
6.1 can act as an input stream and as an output stream: Public randomaccessfile (file file, String mode)
6.2 supports reading and writing from the beginning of a file. If the output file does not exist, create it directly. If present, the content of the original file is overwritten.
6.3 Supports "insert" at any location.

An analysis of Io flow 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.