How to handle text I/O in Java
Use the scanner class to read text data and write text data using the PrintWriter class
Example:
Public classIO { Public Static voidMain (String [] args)throwsFileNotFoundException {//printwriter printwriter = new PrintWriter ("123.txt"); Output Text data//printwriter.print ("Chenzquan");//printwriter.close ();Scanner input =NewScanner (NewFile ("123.txt"));//Enter text dataSystem.out.print (Input.nextline ()); }}
Text I/O needs to be encoded, decoded, and binary I/O is not required, so binary I/O is faster
Binary I/O classes
Methods of the InputStream class
OutputStream class method
FileInputStream and FileOutputStream
FileInputStream classes and FileOutputStream classes for reading/writing bytes from/to files
FileInputStream
FileOutputStream
Public classTestfilestream { Public Static voidMain (String [] args)throwsFileNotFoundException, IOException {Try(FileOutputStream FileOutputStream =NewFileOutputStream ("Temp.dat"); ){ for(inti=0;i<100; i++) {fileoutputstream.write (i); } } Try(FileInputStream FileInputStream =NewFileInputStream ("Temp.dat");){ intvalue; while((Value=fileinputstream.read ())! =-1) {System.out.print (value+ " "); } } }}
DataInputStream and Dataoutputstresam
DataInputStream
Implementing the Datainput Interface
DataOutputStream
Implementing the DataOutput Interface
Creating DataInputStream classes and DataOutputStream classes
Example:
Example:
Public classTestdatastream { Public Static voidMain (String [] args)throwsFileNotFoundException, IOException {Try(DataOutputStream DataOutputStream =NewDataOutputStream (NewFileOutputStream ("Temp.dat"));) {Dataoutputstream.writeutf ("John"); Dataoutputstream.writedouble (85.5); Dataoutputstream.writeutf ("Chenzquan"); Dataoutputstream.writedouble (100.0); } Try(DataInputStream DataInputStream =NewDataInputStream (NewFileInputStream ("Temp.dat"));) {System.out.println (Datainputstream.readutf () )+ " " +datainputstream.readdouble ()); System.out.println (Datainputstream.readutf ()+ " " +datainputstream.readdouble ()); } }}
The DataInputStream class and the DataOutputStream class read and write Java primitive type values and strings in a machine-platform-agnostic way, so one machine writes the data and can read the file on another
Bufferedinputstream class and Bufferedoutputstream class
They can increase the speed of input and output by reducing the number of disk reads and writes
When using Bufferedinputstream, the entire block of data on the disk is read into the in-memory buffer at once, and then the individual data is passed from the buffer to the program
When using Bufferedoutputstream, individual data is written into the buffer, and when the buffer is full, the data of the buffer is written to disk once
Java binary I/O processing