Say in front: IO stream is used to manipulate file, so first say file
First, the file class:
Abstract representation of file and directory path names.
The file class can manipulate only the properties of a file, and the contents of the files cannot be manipulated.
1. Function: Used to operate on disk files. Delete, create, and so on. 2. Three types of constructors:
① directly into a path, get a file or a folder
File File1 = new file ("F:\\test");
② The first parameter passed into the parent path, the second parameter passed in a subpath, or a file
File File2 = new file ("F:\\test", "test.txt");
③ the first argument to the file file, the second parameter to the sub-path, or to a
File File3 = new file (file1, "test.txt");
3. The representation of the path:
Folder segmentation can be used "/", usually used in Linux systems, Windows can also be used
"\ \" is commonly used in Windows systems, note that ' \ ' needs to be escaped
4. Several common methods to be aware of
①:.delete () Delete file Delete succeeds true Delete fails false; If folder is deleted, this folder cannot have child content
②:createnewfile () Create a new file creation failure returns false requires the specified new file name to be determined by calling his file object, instead of passing arguments, not being able to create a successful need to catch an exception
③:mkdir: Only one level of directory can be created, if the second-to-last directory does not exist, the creation fails; Mkdirs: You can create multi-level catalogs that can be created sequentially, no matter how many layers do not exist.
④:list () returns the name of all files and folders in the current directory, with the return value type string[]
string[] List = file1.list (); for string : List) { System. out. println (string);}
An implementation class object that can be passed into the FilenameFilter interface in a parameter, indicating traversal filtering for all files in the list
You need to override the Accept method if you keep the current file return True if you do not return the current file to False
string[] List1 = File1.list (NewFilenameFilter ()) {@Override PublicBoolean Accept (File dir, String name) {//dir: Indicates the parent path containing the current folder//Name: Indicates the current file name if(Name.endswith (". txt")) {return true; }Else{return false; }}); for(String string1:list1) {System. out. println (string1);}
⑤: Returns the path of all files and folders in the current directory, with a return value of type file[]
file[] files = file1.listfiles (); for (File file:files) { System. out. println (file+"----"+File.getname ());}
You can also filter your files
① filter using FilenameFilter () as with List ()
② filtering using the implementation class of the FileFilter interface
file[] Files1 = File1.listfiles (NewFileFilter () {@Override PublicBoolean Accept (File pathname) {//TODO auto-generated Method Stub if(Pathname.getname (). EndsWith (". txt")) {return true; }Else{return false; }}); for(File filen:files1) {System. out. println (filen+"----"+filen.getname ());}
The classification of IO stream: 1. Depending on the direction of the flow: input stream and output stream 2. Depending on the size of the read text: byte stream and Character stream (bytes read, read in Chinese is easy to garbled; character streams are read by character and are typically used to read Chinese 3.) based on the Read method: node stream and cache stream three, BYTE stream Java.io.InputStream Java,io,outputstream1.fileinputstream class
① the stream inherits from the InputStream used to read data from a file, its objects can be created with the keyword new.
② Construction Method
You can use the file name of a string type to create an input stream object to read the file:
FileInputStream f = new FileInputStream ("C:/java/hello");
You can also use a file object to create an input stream object to read the file. We first have to use the file () method to create a Document object:
File F = new file ("C:/java/hello");
FileInputStream out = new FileInputStream (f);
③ Common methods
Available (): Returns the number of bytes that the next method that is called on this input stream can be read from this input stream without being blocked. Returns an integer value.
Read (int R): This method reads the specified byte of data from the InputStream object. Returns an integer value. Returns the next byte of data, or 1 if it has reached the end.
Read (byte[] b): reads up to b.length bytes of data from this input stream into a byte array
Close (): Closes this file input stream and frees all system resources related to this stream. Throw IOException exception
2.FileOutStream
① This class is used to create a file and write data to the file.
If the stream does not exist before the file is opened for output, the stream creates the file.
② Construction Method
Create an output stream object using the file name of the string type:
OutputStream f = new FileOutputStream ("C:/java/hello");
You can also use a file object to create an output stream to write a file. We first have to use the file () method to create a Document object:
File F = new file ("C:/java/hello");
OutputStream f = new FileOutputStream (f);
③ Common methods
Write (int b): Writes the specified bytes to this file output stream.
Write (byte[] b): writes B.length bytes from a specified byte array to this file output stream.
3, Bufferedinputstream, Bufferedoutputstream
Inherit from FilterInputStream, Filteroutputstream
1. Function: The basic stream based on the packaging, read or write to the file, will be done through the cache.
That is, the content is written to the buffer, the buffer is full and then read or write operations
Can greatly reduce the number of file operations, improve write efficiency
2. Use of cache streams:
Packaging based on the underlying stream:
New Bufferedinputstream (New FileInputStream ("F:\\test\\test.txt"));
This is what we call the IO chain, which needs to close the outermost stream when IO is closed, and the inner laminar flow will automatically close
3. Using Bufferedoutstream, the Flush () method is usually called when closing;
Indicates that the buffer is flushed before closing, and the contents of the buffer remaining are written to the file;
Actually the close () method comes with a refresh, which is a habit.
4.DataInputStream and DataOutputStream
1. Inherit from FilterInputStream and Filteroutstream, respectively
2. Special:
① using binary to read and write files
② can read and write directly to basic data types in Java compared to basic streams
3. In addition, if the operation of a file is a binary file, you need to use DataInputStream instead of FileInputStream
Do not replace or can read) Similarly, the stream of the data series has the same read and write methods as the basic flow operation
4. Files written with data stream can only be read with data stream, cannot use basic stream read
5. Several unique methods compared to the basic flow
readUTF (): reads two bytes first, returns this string as a string
READINT (): reads four input bytes and returns an int value
Readdouble (): reads eight input bytes and returns a double value.
6. The method above, if this stream reaches the end before all bytes are read, throws
Java.io.EOFException exception; Eof:end of FILE
Https://www.cnblogs.com/yiwangzhibujian/p/7107084.html (explains in detail why the exception is thrown)
Self-Understanding Solution:
Public classdemo04_datainoutstream2 { Public Static voidMain (string[] args) {DataInputStream dis=NULL; FileInputStream FIS=NULL; Try{FIS=NewFileInputStream ("F:\\test\\demo02_io.class"); if(Fis.available ()! =0) {dis=NewDataInputStream (FIS); }Else{System. out. println ("The file has no readable content! "); } Try { while(true) {System. out. println (Dis.readint ()); }} Catch(eofexception e) {System. out. println ("will definitely throw this exception, indicating that the target file has been read, there is no readable content, we do not do any processing on the good! "); } } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{ Try{dis.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }}
First article:
Https://www.cnblogs.com/ouhaitao/p/7683568.html
1ObjectInputStream Ois =NULL; 2FileInputStream fis=NewFileInputStream (filePath);3 //When there is content in the file 4 if(Fis.available ()! =0) 5OIS =NewObjectInputStream (FIS);6 Else{ 7System. out. println ("the file is empty!"); 8 return ; 9 }Ten Try{ One while(true) ASystem. out. println ((Student) ois.readobject ()); -}Catch(eofexception e) { -}
The principle is: first use the basic flow to determine whether the file is still readable content, only in the judgement of a readable content is to instantiate a
High-level streaming object, this thing again to read, when read and then error will be just manual in read ... () method to catch the Eofexceptiion this exception, do not deal with it.
Second article:
46448877
5.objectinputstream/objectoutputstream
1. Inheriting Java.io.InputStream and Java.io.OutputStream
2. The same as the basic flow, you can use the Read write method directly
3. Methods that can use the data stream
4. Special methods: ReadObject () and WriteObject ()
Serialization and deserialization of objects
1. Serialization of objects: the process of persisting objects in a program to persist in a file Objectoutstream
2. Deserialization of objects: the stored object in the file is re-read to the procedure in the program. ObjectInputStream
If you want to serialize an entity class object, the entity class needs to implement the serializable (serializable) interface.
Add a serialized version number private static final long serialversionuid = 4992258028211704199L;
If you do not add a serialized version number, when you serialize an object, if the entity class attributes are added or deleted, then the deserialization will cause an error
Java.io.InvalidClassException, because the system thinks this is not the same class
Note that although the serialization of objects is called, these two methods of ReadObject () and writeobject () can be used to directly pass in a collection of objects
The ReadObject () and WriteObject () methods also exist eofexception this anomaly, the solution is the same as
Methods such as Readint () in DataInputStream and DataOutputStream
Http://note.youdao.com/noteshare?id=506c27323c6b8a0b6cf3d1f7f97639eb&sub=C87F25CC0E7342558556C89380D7E2AF
Four characters Stream 1. Reader, Writer
1. When processing a data unit, a single character is used as the unit, and the byte stream is a unit of bytes
2. Base class for characters: Reader, Writer (abstract class)
FileReader, FileWrite is a two-character basic stream that inherits directly from the abstract class.
3, FileReader, filewrite when reading and writing files, can only use the system default encoding format;
Unable to specify the encoding, if the file format is inconsistent with the system default format, then using both methods to read and write will cause Chinese garbled
4. Although not the cache stream, but not flush () will cause the write not to read out
2.InputStreamReader, OutputStreamWriter
1. Stream bytes to character streams while supporting custom read and write encoding formats
2. Common encoding formats
ASCLL: American Standard message code;
Iso8859-1: West European Code;
ANSI encoding, can be divided into many kinds:
Simplified Chinese: GB2312, GBK
Traditional Chinese: big-5
Japanese-Chinese ...
Unicode encoding: International standard Code, compatible with most national encoding formats
Can be divided into: UTF-6, UTF-8, UTF-16
The following two lines break a utf-8-formatted string into a character array B, and then use new string (b, "GBK") to generate a new GBK-formatted string s1
String s = "Chinese FDHASFDJ";
Byte[] B = s.getbytes ("UTF-8");
string S1 = new String (b, "GBK");
3.BufferedReader, BufferedWriter
BufferedWriter and BufferedReader output input streams for characters with default buffering, because there is a buffer so that it is more efficient than no buffers.
1, BufferedWriter class
Construction method: BufferedWriter bf = new BufferedWriter (Writer out);
Primary method: void Write (char ch);//write a single character.
void Write (char []cbuf,int off,int len)//writes a portion of the character data.
void Write (String s,int off,int len)//writes a portion of the string.
void NewLine ()//writes a line delimiter.
void Flush ();//refreshes the buffer in the stream. Write the buffered data to the destination file.
void close ();//closes the stream and refreshes it before closing.
2, BufferedReader class.
Construction method: BufferedReader br = new Bufferreader (Reader in);
Main methods: int read ();//Read single character.
int read (char[] cbuf,int off,int len);//reads a character into a part of the array. Returns the number of characters read. Reach the tail, return-1.
String ReadLine (); Reads a line of text.
void Close (); Closes the stream. and frees all resources associated with the stream.
Java IO Flow Summary