Java input and output

Source: Internet
Author: User

Note: This article is for the author to learn the summary, if there are errors please forgive and criticize and point out

1. Input and output stream

Computer storage files are physically stored in binary form, according to the logical differences generally divided into the following two kinds:

Text files: Each character corresponds to an ASCII (Unicode) code that is written in binary form to the disk, where the text and binary are translated in a common encoding such as Unicode (ASCII). A text editor can open a text file.

Binaries: Disks are also saved in binary, but translations are no longer common encoding methods such as Unicode (ASCII), and are defined by different programs themselves. The text editor opens a garbled file.

Text files are read and written using character streams (char-based chars), and binary files are read and written using byte-stream bytes. Figure 1 is a common byte stream of each class, figure 2 is a common character stream each class, Figure 3 is the input and output stream of some commonly used interfaces.

Figure 1 Common byte stream hierarchy

Figure 2 Common character stream hierarchies

Figure 3 Common interfaces for input and output streams

2. text file read/write

Reader (abstract Class) is the parent of the character input stream, and Writer (abstract class) is the parent class of the character output stream. A character stream is read and written in characters (char), processed one Unicode at a time, and its underlying is still the basic byte stream. In layman's terms, a encoding is used to convert a character into a binary disk, and the binary is read and converted into characters in the same encoding. Therefore, a character stream can only manipulate text files.

2.0 Character Conversion Flow principle

InputStreamReader: You can set the character set to convert bytes to characters and read this encoding. Constructors: InputStreamReader (InputStream in,string charsetname) and InputStreamReader (InputStream in)--system default character set

OutputStreamWriter: You can set character sets, convert characters to bytes in this encoding, and write them out. Constructors: OutputStreamWriter (OutputStream out,string charsetname) and OutputStreamWriter (OutputStream out)--system default character set

2.1 Text output (PrintWriter)

Common constructors:

printwriter (file file) printwriter (string filename) printwriter (file file,string encoding) PrintWriter (string Filename,string encoding) PrintWriter (writer writer) PrintWriter (writer writer,boolean  AutoFlush) PrintWriter (OutputStream out) PrintWriter (OutputStream out,boolean autoflush)

Common methods:

voidPrint (Object obj)//Print the ToString string of objvoidprint (String s)voidprintln (String s)voidPrintChar[] s)voidPrintCharc)voidPrintinti)voidPrintLongl)voidPrintfloatf)voidPrintDoubled)voidPrintBooleanb//print in text FormatvoidPrint (String format,object ... args)//prints a string in the specified format

Example:

PrintWriter out=New printwriter ("C:\\users\\administrator\\desktop\\raf.dat", "UTF-8"); PrintWriterout =new printwriter (new OutputStreamWriter (New  FileOutputStream (" C:\\users\\administrator\\desktop\\raf.dat ")," UTF-8 "),true);

2.2 Text Read-in

(1) Scanner Class (Scanner (InputStream in,string charsetname))

Try (Scanner in=new Scanner (new FileInputStream ("C:\\users\\administrator\\desktop\\raf.dat"), " UTF-8 "))
{
while (In.hasnextline ()) { System.out.println (In.nextline ());} }

(2) Short text read into a string

String content=New string (Files.readallbytes (Paths.get ("C:\\users\\administrator\\desktop\\raf.dat")) , "UTF-8");

(3) Short text line-by-line reading

List<string> Lines=files.readalllines (Paths.get ("C:\\users\\administrator\\desktop\\raf.dat"), Standardcharsets.utf_8);  for (String s:lines) {   System.out.println (s);}

(4) Large files will be lazily processed into a Stream<string> object (JDK1.8).

Try (Stream<string> lines=files.lines (Paths.get ("C:\\users\\administrator\\desktop\\raf.dat"), Standardcharsets.utf_8)) {      ...       }

(5) BufferedReader class

FileInputStream fin=New fileinputstream ("C:\\users\\administrator\\desktop\\raf.dat"); Nputstreamreader ISR=new  InputStreamReader (fin,standardcharsets.utf_8); Try (BufferedReader in=new  BufferedReader (ISR);) {   String line;     while ((Line=in.readline ()) =null) {       System.out.println (line);       }}
3. Binary file read/write

3.0 Datainput and DataOutput interfaces

Datainput Interface: A number (group), character, Boolean, and string to read in binary format.

Common methods: WriteByte, Writeint, Writeshort, Writelong, Writefloat, writedouble, Writechar, Writeboolean, WriteChars, WriteUTF (only write a string for the Java Virtual machine)

DataOutput interface: Used to write numbers (groups), characters, Booleans, and strings in binary format.

Common methods: ReadByte, ReadInt, Readshort, Readlong, Readfloat, readdouble, ReadChar, Readboolean, readUTF, skipbytes (int n)

3.1 DataInputStream and DataOutputStream for reading and writing

Try (DataOutputStream out=new dataoutputstream (new fileoutputstream ("c:\\users\\administrator\\ Desktop\\raf.dat ")){   out.writeint (222);   Out.writedouble (222.22);   Out.writeutf ("Guo No");} //////////////////////////////////////////////////////////////////////// Try (DataInputStream in=new datainputstream (new fileinputstream ("c:\\users\\administrator\\ Desktop\\raf.dat ")){   System.out.println (In.readint ()+", "+in.readdouble () +", "+In.readutf ( ));}

3.2 Randomaccessfile for Read and write

Randomaccessfile implements both the Datainput and DataOutput interfaces, you can use the second parameter of the constructor R/RW to specify the open mode. There is a file pointer that represents the location of the next byte that will be read into or written out.

Common constructors:

randomaccessfile (File file,string mode) randomaccessfile (String filename,string mode)    // mode:r   rw

Additional Common methods:

Long ): Sets the file pointer to any byte position (0 to file byte length) Getfilepointer: Returns the file pointer current position length () file Bytes Total
Skipbytes (int n): Skips n bytes

Example:

 try  (randomaccessfile raf=new  Randomaccessfile ("C:\\users\\administrator\\desktop\\raf.dat", "RW"  123 123.56 "Guo Wenjing"  //////////////////////////////////////////////////////////////////////////  / try  (Randomaccessfile raf= new  Randomaccessfile ("C:\\users\\administrator\\desktop\\raf.dat", "RW"  + "," +raf.readdouble () + "," +raf.readutf ()); }

3.3 Zip Document

The Java Operations Zip document mainly covers the following four classes: Zipinputstream, Zipoutstream, ZipEntry, ZipFile

(1) write to zip file

New FileOutputStream ("C:\\users\\administrator\\desktop\\gwj1.zip"new  Zipoutputstream ( Foutputstream); Stringline = "GWJ";  for (int i=0;i<3;i++) {    byte[] bytes= (line+i). GetBytes ();    ZipEntry zentry  new zipentry ("No" +i+ ". txt");    Zoutput.putnextentry (zentry);    Zoutput.write (bytes);    Zoutput.closeentry ();} Zoutput.close ();

(2) Read the zip file (both ZipFile and Zipinputstream are OK)

ZipFile zipfile=NewZipFile ("C:\\users\\administrator\\desktop\\gwj1.zip"); ZipEntry entry; Enumeration e=zipfile.entries (); while(E.hasmoreelements ()) {entry=(ZipEntry) e.nextelement (); System.out.println ("-------" +entry.getname () + "-------"); InputStreamReader ISR=NewInputStreamReader (Zipfile.getinputstream (entry), standardcharsets.utf_8);Try(BufferedReader in=NewBufferedReader (ISR);) {String line; while((Line=in.readline ())! =NULL) {System.out.println (line); }   }    }

3.4 Object serialization

(1) Object serialization use

Employee Harry =NewEmployee ("Harry Hacker", 50000, 1989, 10, 1); Manager Carl=NewManager ("Carl cracker", 80000, 1987, 12, 15); carl.setsecretary (Harry); Manager Tony=NewManager ("Tony Tester", 40000, 1990, 3, 15); tony.setsecretary (Harry); Employee[] Staff=NewEmployee[3];staff[0] =carl;staff[1] =harry;staff[2] =Tony; String name= "Guo Wenjing";//Save all employee records to the file Employee.datTry(ObjectOutputStream out =NewObjectOutputStream (NewFileOutputStream ("C:\\users\\administrator\\desktop\\employee.dat")) {out.writeobject (staff); OUT.WRITEUTF (name);}Try(ObjectInputStream in =NewObjectInputStream (NewFileInputStream ("C:\\users\\administrator\\desktop\\employee.dat"))){employee[] Newstaff=(employee[]) in.readobject ();Newstaff[1].raisesalary (10);    for(Employee e:newstaff) System.out.println (e); System.out.println (In.readutf ());}

Note: Employee needs to implement serializable interface. Employee Implements Serializable

(2) Principle of object serialization

    • File format for serialization of objects

Java input and output

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.