File base
The representation of the file and directory abstract path name, which is constructed with a method of four
File Parent,string Child: Creates a file instance from the abstract parent directory.
File (String parent,string child): Creates a file instance from the parent directory.
File (String pathname): Creates a file instance from the specified path.
File (URI path): Creates a file instance from the URI converted to an abstract path.
Listfiles () Method: Returns an abstract path an array group that represents a subkey (file or directory) in a directory
File File = new file ("/home/colin"); file[] Childs = File.listfiles ();
Listfiles (filefilter filter): FileFilter is an abstract pathname filter that can be used to return a subdirectory of the filter requirement
File File = new file ("/home/colin");//has not been considered, Java is not allowed to implement an interface instance, but in the anonymous inner class is implemented interface, such as the FileFilter interface//actually if you look at the compiled code ( You will find a class file in the compiled code that implements this interface and overrides the method of the interface.//So this is a virtual instantiation interface, or an indirect instantiation of the interface. file[] Childs = file.listfiles (new FileFilter () {@Overridepublic Boolean accept (file pathname) {return Pathname.getname ( ). StartsWith (".");});
There is also a listfiles (Filenamefileter filter): Filenamefile is used to detect whether the specified file is contained in a specific directory
Other APIs are relatively simple, get file status, create delete files
Randomaccessfile Random Read and write files
File instances involve only the operation of files, Java provides operations that allow random access to files, and access includes read and write operations, which are pointer-based operations.
Two methods of construction:
Randomaccessfile (File name,string model)
Randomaccessfile (String name,string model)
MODEL specifies the random access operation mode of the file, there are two modes are read-only mode and read-write mode, "R" means that the file access is read-only, "RW" represents the Read and write mode.
Randomaccessfile file = new Randomaccessfile ("/home/colin", "RW");
Write Data:
Write (byte[] b): Writes the specified array B to a random read-write file, to the position of the pointer
Write (byte[] b,int off,int len): Specifies the starting position and length
Write (int n): Writes the low eight bits of N to the file
He also has methods for writing specific attributes: Writeboolean (Boolean B), writeint (int n), writedouble (double v), Writechart (Chart C), Writecharts (String s ), writebyte (int n), writebytes (String s), writefloat (Float t), etc.
Read data:
int read (): reads 1byte (8 bits) into the lower eight bits of int, and a height of 24 is 0. If you read-1, the description reads to the end of the file
int read (byte[] b): reads up to b.length bytes to the array, the return value is the amount of bytes actually read to
int read (byte[] b,int off, int length): Specifies the starting position and read length of the read array
The corresponding read for reading a specific type of data
Readboolean (), Readfloat (), and so on, especially a readline () reads a row at the current position
These are read from the current pointer position.
To release the associated resource: void Close ()
Gets the current Randomaccessfile pointer: Long Getfilepoint (), in bytes, such as if an int is 4 bits
Move current pointer position: void Seek (Long POS)
Skip N Bytes: int sikpbytes (int n): Returns the actual number of bytes skipped, n is negative and does not skip any bytes
Randomaccessfile file = null;try {file = new Randomaccessfile ("/home/colin/test.txt", "RW");//byte[] B = "This is the sample Ra Ndomaccessfile ". GetBytes ();//file.read (b); byte[] B = new Byte[10];while (File.read (b) >0) {System.out.println (new String (b)); System.out.println (File.getfilepointer ());//Gets the file pointer file.skipbytes (1);//Skips one byte per read}} catch (FileNotFoundException E ) {e.printstacktrace ();} Finally{if (file! = null) File.close ();}
Basic IO
Input refers to the direction of the program from the outside, that is, when we need to read the data, use the input.
Output is sent from the program to the outside direction, usually we need to write out the data to the outside world, so the output is used to write data.
Classification of streams
By unit: Byte stream (8bit, picture video, etc.) and character stream (16bit, text)
Depending on the role: node flow (a stream directly acting on text, directly connected to a specific place (disk, memory)) and processing flow (the flow in the outer layer of a node stream, is the connection and encapsulation of an already existing stream, which implements the reading and writing of the data in the function of the encapsulated stream)
More than 40 streams in Java are derived from 4 base classes
Stream of Byte stream characters
Input: InputStream Reader
Output: OutputStream Writer
InputStream and OutputStream
Both are abstract base classes of byte streams that define the basic read and write methods, read (), read (byte[] a,int off,int length), read (byte[] b), write (int b), write (byte[] b) , write (byte[] b,int off, int len)
Reader and writer
Both reader and writer are abstract base classes of character streams that define read and write reading characters. Read (), read (char[] cbuf), read (char[] cbuf,int off, int len), write (char c), write (char[] cbuf), Cbuf (cbuf,int off, int len)
File stream
File byte stream:
The FileOutputStream can be constructed using several methods:
FileOutputStream (File file)
FileOutputStream (String name)
Specifies the file to be written to, and if the file exists, clears the contents of the file
FileOutputStream (File File,boolean append)
FileOutputStream (String Name,boolean append)
If the specified append parameter is true, then if the file being written is present, it is written in the appended way
FileInputStream can be constructed using the following methods:
FileInputStream (File file)
FileOutputStream (String name)
The file byte stream implements the basic read and write of InputStream and OutputStream
Note that if you return-1 when reading, it means that you have read EOF
Using file streams to implement File replication:
File File1 = new file ("/home/colin/hello.py"); File File2 = new file ("/home/colin/hello2.py"); FileInputStream input = null; FileOutputStream output = null;try {input = new FileInputStream (file1); output = new FileOutputStream (file2); byte[] B = new Byte[10];int len = -1;while ((len=input.read (b))!=-1) {output.write (b, 0, Len);}} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally{try { //First off input stream, then off output stream if (inputput! = null) inputput.close (); if (output! = null) Output.close ();} catch ( IOException e) {e.printstacktrace ();}}
FileReader and FileWriter are used in the same way as FileInputStream and FileOutputStream.
Buffered streams
Bufferedinputstream principle: Buffer byte input stream, the internal maintenance of a buffer, the stream will be as long as possible to read a number of bytes to the buffer, and then return one by one to know that the data in the buffer is fully read, thus reducing the number of reads, improve read efficiency, the BIS is a processing flow, This stream provides buffering capabilities. He also provides the mark, reset, and Skip methods
The construction method provided:
Bufferedinputstream (InputStream input)
Bufferedinputstream (inputstream input,int size): size Specifies the buffer size
Bufferedoutputstream principle: Buffered output stream, internal maintenance of a buffer, every time the data is written to the stream, the data is now stored in the buffer, when the buffer is full, the buffer stream will write the data all at once.
The construction method provided:
Bufferedoutputstream (OutputStream out)
Bufferedoutputstream (outputstream out,int size): Specifies the buffer size
Bufferedoutputstream only provides the write and flush () methods, Flush () empties the buffer and forces the data in the buffer to be written.
Using buffered streams for file replication:
Bufferedinputstream bis = null; Bufferedoutputstream bos = null;try {bis = new Bufferedinputstream (New FileInputStream ("/home/colin/hello.py") ); bos = new Bufferedoutputstream (New FileOutputStream ("/home/colin/hello3.py")); int len = -1;byte[] B = new Byt E[10];while ((Len=bis.read (b))!=-1) {bos.write (b, 0, Len);} Bos.flush ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} Finally{try {//First off input stream, then off output stream if (bis! = null) bis.close (); if (bos! = null) Bos.close ();} catch (IOException e) { E.printstacktrace ();}}
BufferedReader and BufferedWriter are the same as the Bufferedinputstream and Bufferedoutputstream implementations, but BufferedWriter provides newline (), Method object flow for writing newline characters
Object serialization: Objects exist in memory, sometimes they need to be saved to disk, or objects are transferred, and so on. This is the time to convert an object into a sequence of bytes, which is called object serialization.
Object deserialization: Sometimes it is necessary to convert a sequence of bytes into a corresponding object, and this process becomes the object's deserialization.
ObjectOutputStream: The output stream used to serialize an object
The construction method provided:
ObjectOutputStream ()
ObjectOutputStream (OutputStream out)
Using its Write method, the object is translated into a sequence of bytes and written out, and the Write method provides such methods as Writeint ().
ObjectInputStream: Used to deserialize an object
The construction method provided:
ObjectInputStream ()
ObjectInputStream (InputStream input)
Read bytes and convert to corresponding object using the ReadObject () method provided by it
The whole idea is to pass on the object and convert the object into a byte stream for transmission, so it is first written through ObjectOutputStream, and the object is written as bytes for transmission. It needs to be read after it is passed to the target location, which converts the transferred bytes into an object.
If you use ObjectOutputStream to serialize the write, you need to serialize the object to implement the Serializable interface, and there is no way for the interface to just serialize flags. Usually implement this interface needs to give a serialversionuid, indicating that the class version, if not the declaration compiler will also be calculated to give a serialversionuid, but different compiler implementations, so if you want to cross-platform, you should display the declaration version number. When the object of the class is serialized to disk, and then the demand changes, changing the properties of the class, then the deserialization will appear invalidclassexception, which will cause incompatibility problems. But when the serialversionuid is the same, the different field is deserialized with the default value of type, which avoids incompatibility problems
Transient keywords: When we serialize the object, the sequence of bytes is often larger, sometimes we can be serialized on an object to ignore some unnecessary properties, so that the serialized byte sequence to be thin, you can declare it as transient, These properties are ignored when serializing.
Instance:
/* Constructs an EMP class, serializes and deserializes its objects */public class Emp implements Serializable {private static final long Serialversionuid = 1l;priv Ate string name;private int age;private double salary;private transient string description; Output NULL public Emp (String name,int age,double salary,string description) {this.name = name when deserializing, using the transient decoration; This.age = Age;this.salary = Salary;this.description = description;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public double getsalary () {return salary;} public void Setsalary (double salary) {this.salary = salary;} Public String GetDescription () {return description;} public void SetDescription (String description) {this.description = description;} @Overridepublic String toString () {return "Emp [name=" +name+ ", age=" +age+ ", salary=" +salary+ ", description=" + description+ "]";}} /* * Serialization of EMP objects and storage */ p ublic static void Testoos () { objectoutputstream oos = null; & nbsp; try { fileoutputstream fos = new FileOutputStream (New File ("/home/colin/oos.obj")); oos = new ObjectOutputStream (FOS); emp emp = new EMP ("Colin", 23, 13000, " I want You!!! "); oos.writeobject (EMP); } catch (FileNotFoundException e) { e.printstacktrace () ; } catch (IOException e) { e.printstacktrace (); }finally{ try { if (oos! = null) oos.close (); } catch ( IOException e) { e.printstacktrace (); } } } /* * Counter-sequence output of stored EMP objects */ public static void Testois () { objectinputstream ois = null; Try { fileinputstream fis = new FileInputStream ("/Home /colin/oos.obj ")); ois = new ObjectInputStream (FIS); emp emp = (EMP) ois.readobject (); system.out.println (emp.getname () + "," +emp.getage () + "," + Emp.getsalary () + "," +emp.getdescription ()); } catch (FileNotFoundException e) { e.printstacktrace (); } catch (IOException e) { e.printstacktrace (); } catch (ClassNotFoundException e) { E.printstacktrace (); } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java IO processing