IO stream in Java

Source: Internet
Author: User
Tags date1 serialization

io stream in JavaAccording to the direction of the flow is divided into the input stream and the output stream according to the size of the read text stream and the character stream byte stream bytes read read Chinese when it is easy to garbled characters stream by character reading is usually used to read the Chinese based on the read way node stream and cache stream

file input stream and output stream (FileInputStream fileoutputstream)
FileInputStream fis=null; FileOutputStream fos=null; Try {        fis=new fileinputstream ("D:\\test.txt");     } catch (IOException e) {
E.printstacktrace ();
}

If the second argument is omitted, or false is passed in, the file is emptied each time it is written, and written from the beginning of the file if the second argument passes in true, the file is not emptied and the end of the article is added
fos=New fileoutputstream ("D:\\out.txt",true);

Output mode
Byte -by-byte read byteintN=-1; while((N=fis.read ())!=-1) {sb.append (Char) n);} Declare a byte array directly as the length of the input stream and read out all the text at oncebyte[] bytes=New byte[Fis.available ()];fis.read (bytes); Sb.append (NewString (bytes)); Read 1024 bytes at a timebyte[] bytes=New byte[1024];intN=-1; while((N=fis.read (bytes))!=-1) {sb.append (NewString (bytes));} Converts a string to a byte array and inputs the file through the output stream sb.reverse (); Fos.write (Sb.tostring (). GetBytes ()); System.out.println (SB);

} Catch(FileNotFoundException e) {e.printstacktrace ();}Catch(IOException e) {e.printstacktrace ();}finally{

}

  

finallyA piece of code that executes regardless of whether the above code will occur is typically used to close various resources to transfer pictures
 public  static  void   main (string[] args) { try   {fileinputstream fis  =new  fileinputstream (" D:\\test.txt  "); FileOutputStream Fos  =new  fileoutputstream ("D:\\test.txt" );   int  n=-1;  while  ((N=fis.read ())!=-1 catch   (FileNotFoundException e) { E.printstacktrace ();}  catch   (IOException e) {e.printstacktrace ( );} 
}

buffered input stream and buffered output stream (Bufferedinputstream bufferedoutputstream)

Role

Packaging on the basis of the basic stream, reading or writing to the file, will be done through the cache, that is, the content is written to the buffer, the buffer is full, but read or write operations can greatly reduce the number of file operations, improve write efficiency
        FileInputStream fis=null;        FileOutputStream fos=null;        Bufferedinputstream bis=null;        Bufferedoutputstream BOS=null;         Long date1=new  Date (). GetTime ();         Try  {
=new bufferedinputstream (new FileInputStream ("D:\\test.txt"));// This notation, we become the IO chain, When IO is off, only the outermost stream needs to be closed, and the inner laminar flow will automatically close
Bos=NewBufferedoutputstream (NewFileOutputStream ("D:\\out.txt",true)); StringBuffer SB=NewStringBuffer (); //Byte -by-byte read byte            intN=-1;  while((N=fis.read ())!=-1) {sb.append (Char) n);            } System.out.println (SB); LongDate2=NewDate (). GetTime (); System.out.println ("--------" + (date1-date2)); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally {            Try {                           //fis.close ();Bis.close (); //fos.close ();Bos.flush ();//at the end of the program, flush the cache stream and write the content that is not full in the cache stream to the fileBos.close ();//call the Close method to automatically refresh}Catch(IOException e) {E.printstacktrace (); }                }  

Bufferedoutputstream usually calls Bos.flush () before shutting down, indicating that the cache stream is flushed before it is closed, that content that is not full in the cache stream is written to a file but the general close () method automatically refreshes the cached streams data input stream and data output stream (DataInputStream dataoutputstream)

Use binary to read and write to a file you can read and write to the basic data types in Java as opposed to the basic stream in addition, if the file being manipulated is a binary file, you need to use DataOutputStream instead of FileOutputStream Note Using DataOutputStream to write files to binary files can only be read using DataInputStream
String name= "HHH"; intAge=23; Doubleheight=134.6; String Ads= "Yantai"; DataInputStream Dis=NULL; DataOutputStream dos=NULL; Try{dos=NewDataOutputStream (NewFileOutputStream ("D:\\test.txt"));        DOS.WRITEUTF (name);        Dos.writeint (age);        dos.writedouble (height);                Dos.writeutf (ADS); Dis=NewDataInputStream (NewFileInputStream ("D:\\tout.txt")); String uname=Dis.readutf (); intUage =Dis.readint (); DoubleUheight =dis.readdouble (); String uads=Dis.readutf (); System.out.println (uname+ "---" +uage+ "---" +uheight+ "---" +uads); } Catch(FileNotFoundException e) {e.printstacktrace (); }Catch(IOException e) {e.printstacktrace (); }finally{            Try{dis.close ();                Dos.flush ();            Dos.close (); } Catch(IOException e) {e.printstacktrace (); }                    }}        

object input stream and object output stream (ObjectInputStream objectoutputstream)

directly inherit from import Java.io.outputStream;  Abstract class is the same as the basic flow, you can use the ReadWrite method to read and write the same as DataInputStream, can read and write directly in Java basic data Type Readint () writedouble () can be used only readobject () WriteObject () manipulating objects directly Objects need to be serialized and deserializedSerialization the process of persisting an object in a program into a file, and deserializing the object in the file back into the program if, in order to sequence an object, the entity class must implement a serializable interface class person implements Serial izable{} Note that when an entity class implements a serializable interface, it is possible to add a serialized version number ID that automatically generates a static property such as private static final long Serialversionuid = 2545980 081191079819L; After adding, you can use the ID to indicate that the object that is manipulated when serializing and deserializing is the same object if you do not add an ID the deserialization produces an error if the serialization adds a new object
 Public Static voidMain (string[] args) {person Zhangsan=NewPerson ("Zhang San", 28, 178.5, "Yantai"); ObjectInputStream Ois=NULL; ObjectOutputStream Oos=NULL; Try{Oos=NewObjectOutputStream (NewFileOutputStream ("D:\\test.txt"));                                    Oos.writeobject (Zhangsan); Ois=NewObjectInputStream (NewFileInputStream ("D:\\test.txt")); Person P=(person) ois.readobject ();                                    SYSTEM.OUT.PRINTLN (P); } Catch(FileNotFoundException e) {e.printstacktrace (); }Catch(IOException e) {e.printstacktrace (); } Catch(ClassNotFoundException e) {e.printstacktrace (); }finally {            Try{ois.close ();            Oos.close (); } Catch(IOException e) {e.printstacktrace (); }                    }        }    }
classPersonImplementsserializable{Private Static Final LongSerialversionuid = 2545980081191079819L; PrivateString name;  PublicString GetName () {returnname; }         Public voidsetName (String name) { This. Name =name; }         PublicPerson (String name) {Super();  This. Name =name; }    }    

input character stream and output character stream (FileWriter FileReader)The character stream in the processing data unit is, in a single character unit, while the byte stream, in a word abstracted as the unit character of the base class reader writer These two are abstract classes Filewriter_filereaderfilereader FileWriter is directly inherited from the abstract class two characters basic stream FileReader FileWriter when reading and writing files, can only use the system default encoding format cannot specify the encoding, if the file format is different from the system default format, then using both methods read and write will cause Chinese garbled
     Public Static voidMain (string[] args) {FileWriter fw=NULL; FileReader FR=NULL; Try{FW=NewFileWriter ("D:/io.txt"); String s= "1358KKKKK will";              for(inti = 0; I < s.length (); i++) {fw.write (S.charat (i));            } fw.flush (); Fr=NewFileReader ("D:/io.txt"); intN=0; StringBuffer SB=NewStringBuffer ();  while((N=fr.read ())!=-1) {sb.append (Char) n);                                } System.out.println (Sb.tostring ()); } Catch(IOException e) {e.printstacktrace (); }finally {            Try{fw.close (); } Catch(IOException e) {e.printstacktrace (); }        }                }

InputStreamReader OutputStreamWriter1. Stream bytes to character streams while supporting custom read and write encoding formats 2. Common encoding Format ASCII American Standard Information Code iso8859-1 European code ANSI code is divided into a variety of Simplified Chinese GB2312 GBK Traditional Chinese big-5 Unicode encoding International standard codes compatible with most countries the encoding format can be divided into UTF-6 UTF-8 UTF-16 character buffered input stream and character buffered output stream (BufferedWriter BufferedReader)
bw=New  bufferedwriter (new outputstreamwriter(new fileoutputstream ("D :/out.txt ")," UTF-8 "))   ;//indicates that the string is decoded with UTF-8 to a byte array bw.write (Sb.tostring ()+" KKKKKKKKKKKKKKKKKKKKK ");

The original string s is the encoded format of the UTF-8
string S=sb.tostring () + "KKKKKKKKKKKKKKKKKKKKK"; s=new String (s.getbytes ("UTF-8"), "GBK"

Finally, a UTF-8 string, encoded into a GBK-formatted string, is decoded

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.