Various streams in java (the instructor's youdao cloud Note), java youdao

Source: Internet
Author: User
Tags object serialization

Various streams in java (the instructor's youdao cloud Note), java youdao
Memory Operation stream-the file operation stream before the byte is based on the input and output of the file. When the output location changes to memory, it is called the memory operation stream. In this case, you must use the memory stream to complete the input and output operations of the memory. If some temporary files need to be generated during the running of the program, you can use virtual files. directly operating the files on the disk consumes a lot of performance, and using the memory stream can improve the performance; jdk provides a memory stream to implement functions similar to memory virtual files. • ByteArrayInputStream: writes content to the memory • ByteArrayOutputStream: writes ByteArrayInputStream from the memory: constructor: • public ByteArrayInputStream (byte [] buf ): all content • public ByteArrayInputStream (byte [] buf, int offset, int length): content within the specified range ByteArrayOutputStream: • public ByteArrayOutputStream () public class ByteArrayDemo {public static void main (String [] args) throws Exception {String info = "helloworld"; InputStream input = new ByteAr RayInputStream (info. getBytes (); OutputStream output = new ByteArrayOutputStream (); int temp = 0; while (temp = input. read ())! =-1) {output. write (Character. toUpperCase (char) temp);} String str = output. toString (); // extract the content input. close (); // close useless output. close (); // invalid System. out. println (str) ;}} print stream thinking: If you want to complete a string, boolean, or dense data output, is it convenient to use OutputStream? It must be inconvenient. Because OutputStream can only operate on byte data, it is difficult to operate other data types. Therefore, two types are added to the Java IO package to solve this problem: printStream and PrintWriter. A print stream can print any data type. Such as integer, decimal, and string. Observe the construction of the PrintStream class: public PrintStream (File file) throws FileNotFoundExceptionpublic PrintStream (OutputStream out) • Although PrintStream is a subclass of OutputStream, it still needs an OutputStream object during instantiation. Unlike other output streams, PrintStream never throws an IOException ;. In addition, to automatically refresh, you can create a PrintStream. This means that the flush method can be automatically called after the byte array is written. You can call one of the println methods, or write a line break or byte ('\ n '). Public PrintStream (OutputStream out) {// this (out, false) is not automatically refreshed;} both PrintWriter and PrintStream belong to the output stream, respectively for characters and bytes. PrintWriter and PrintStream reload print () and println () are used for output of multiple data types. • The parameters in print () cannot be blank. println () can be output by PrintWriter and PrintStream without throwing an exception. PrintStream has the automatic flush function to call the println method; public class PrintStreamDemo {public static void main (String [] args) throws Exception {PrintStream out = new PrintStream (new FileOutputStream (new File ("d:" + File. separator + "test.txt"); out. print (3 + "+" + 2 + "="); out. println (2 + 3); out. println ("Hello itcast! "); Out. close () ;}} after Java5, The PrintStream class adopts the printf () method for formatting output operations. However, the output data type must be specified during formatting: character Description % s indicates the content is a string % d indicates the content is an integer % f indicates the content is a decimal % c indicates the content is a character, of course, you can also use "% s" to represent all public class Demo {public static void main (String [] args) {String s1 = ""; int age = 17; float pi = 3.14F; char c = 'U'; System. out. printf ("Name: % s, age: % d, PI = % f, character: % c", s1, age, pi, c); System. out. printf ("Name: % s, age: % s, PI = % s, character: % s", s1, age, pi, c );}} A pipe stream is also called a thread communication stream. It is mainly used for communication between two threads: • PipedOutputStream: Pipe Pipeline output stream • PipedInputStream: Pipeline input stream PipedOutputStream has a method: • void connect (PipedInputStream pis) throws IOException: method used to connect pipeline PipedInputStream: • void connect (PipedOutputStream pos) throws IOException: class Send implements Runnable {private PipedOutputStream pos = null; public Send () {pos = new PipedOutputStream ();} public PipedOutputStream getPos () {return pos ;} public void run () {String s = "peak/Peak invitation Watching the pigs fed by the village chief "; pos. write (s. getBytes (); pos. close () ;}} receiver class Receive implements Runnable {private PipedInputStream pis = null; public Receive () {pis = new PipedInputStream ();} public PipedInputStream getPis () {return pis;} public void run () {byte [] bys = new byte [1024]; int len = pis. read (bys); pis. close (); System. out. println ("-->" + new String (bys, 0, len) ;}} public class PipedDemo {public st Atic void main (String [] args) {Send send Send = new send (); Receive rec = new Receive (); try {Send. getPos (). connect (rec. getPis ();} catch (IOException e) {e. printStackTrace ();} new Thread (send ). start (); new Thread (rec ). start () ;}} processes stream node streams: • data can be read and written from or to a specific place. It is used to directly operate the stream class corresponding to the target device. The IO source or target corresponding to the node stream class is called a stream node. Stream processing: • connection and encapsulation of existing streams, data read and write through calling the encapsulation stream function. The constructor of stream processing always includes one other stream object as a parameter. A stream object is encapsulated multiple times by other streams, which is called a stream link. • When stream processing is used, the input/output resources are closed. You only need to close the upper-layer stream. When the upper-layer stream is disabled, the system will close the processed node stream by default. The buffer stream needs to be connected to the corresponding node stream. It provides the buffer function for read and write data, improves the Read and Write efficiency, and adds some new methods. Four buffer streams • BufferedReader (Reader in) • BufferedReader (Reader in, int sz) // sz indicates the size of the custom buffer • BufferedWriter (Writer out) • BufferedWriter (Writer out, int sz) • BufferedInputStream (InputStream in, int sz) • BufferedOutputStream (OutputStream out, int sz) bufferedReader provides the readLine Method for reading a line of strings. BufferedWriter provides the newLine Method for writing a row separator. Equivalent //. writer ("\ r \ n"); For the buffer stream output, the written data is first buffered in the memory. Using the flush method, the data in the memory will be immediately written. Public static void main (String [] args) throws Exception {BufferedReader br = new BufferedReader (new FileReader ("test.txt ")); bufferedWriter bw = new BufferedWriter (new FileWriter ("AA.txt"); String line = null; while (line = br. readLine ())! = Null) {// read a row bw. write (line); // write a row bw. newLine (); // line feed after writing a line} bw. close (); br. close () ;}convert stream byte stream ----> bytes stream • InputStreamReader byte input stream --> character input stream • OutputStreamWriter byte output stream --> character output stream InputStreamReader needs to "intercept" with InputStream "; the OutputStreamWriter and OutputStream need to "intercept" the conversion stream. During construction, you can specify its encoding set: • InputStreamReader in = new InputStreamReader (Sytem. in, "ISO8859_1"); to achieve the highest efficiency, you can consider packing InputStreamReader in BufferedReader. For example: • BufferedReader in = new BufferedReader (new InputStreamReader (System. in); public static void main (String [] args) {try {OutputStreamWriter osw = new OutputStreamWriter (new FileOutputStream ("path"); osw. write ("mircosoftibmsunapplehp"); System. out. println (osw. getEncoding (); osw. close (); osw = new OutputStreamWriter (new FileOutputStream ("path", true), "ISO8859_1"); // latin-1 osw. write ("mircosoft Ibmsunapplehp "); System. out. println (osw. getEncoding (); osw. close ();} catch (IOException e) {e. printStackTrace () ;}} public static void main (String args []) {InputStreamReader isr = new InputStreamReader (System. in); BufferedReader br = new BufferedReader (isr); String s = null; try {s = br. readLine (); while (s! = Null) {if (s. equalsIgnoreCase ("exit") break; System. out. println (s. toUpperCase (); s = br. readLine ();} br. close ();} catch (IOException e) {e. printStackTrace () ;}} data operation stream and platform-independent data operation stream: DataInputStream and DataOutputStream inherit from InputStream and OutputStream respectively, which are processing streams, you need to "intercept" them on InputStream and OutputStream node streams respectively. DataInputStream and DataOutputStream provide methods to store Java raw data (such as int and boolean. Constructor: • DataInputStream (InputStream in) • DataOutputStream (OutputStream out);/the read sequence of the ** data stream ** must be consistent with the input sequence, * **/public class DataOutputStreamDemo {public static void main (String [] args) throws Exception {ByteArrayOutputStream baos = new ByteArrayOutputStream (); DataOutputStream dos = new DataOutputStream (baos ); double d = Math. random (); System. out. println ("-->" + d); dos. writeDouble (d); dos. writeBoolean (t Rue); dos. writeFloat (3.14f); ByteArrayInputStream bais = new ByteArrayInputStream (baos. toByteArray (); DataInputStream dis = new DataInputStream (bais); System. out. println (dis. readBoolean (); // true System. out. println (dis. readDouble (); // random number System. out. println (dis. readFloat (); dos. close (); dis. close () ;}} merge stream SequenceInputStream: Merge the content of two files into one file. The method provided by this class is: • SequenceInputStream (InputStream s1, InputStrea M s2): Creates a merged Stream object based on two bytes of input stream objects. Public class SequenceInputStreamDemo {public static void main (String [] args) {String src1 = "d:/a.txt"; String src2 = "d:/B .txt "; string dest = "d:/AB .txt"; try (InputStream is1 = new FileInputStream (src1); InputStream is2 = new FileInputStream (src2); OutputStream OS = new FileOutputStream (dest ); sequenceInputStream sis = new SequenceInputStream (is1, is2);) {byte [] bys = new byte [1024]; int le N = 0; while (len = sis. read (bys ))! =-1) {OS. write (bys, 0, len) ;}} catch (Exception e) {e. printStackTrace () ;}} common encoding ISO8859-1, UTF-8, Unicode, GBK, GB2312, GB18030; ISO8859-1, also known as Latin-1 or "Western European language", is a single-byte encoding, up to 0 ~ 255, used in the English system, does not support Chinese; gbk/gb2312/gb18030: China's international code, dedicated to represent Chinese characters, dubyte encoding, GBK represents Chinese Simplified and traditional, gb2312 indicates simplified, and GBK is compatible with gb2312. Gb18030 is an enhanced version of GBK encoding. unicode: This encoding is used by java and is also the most standard encoding, represented in hexadecimal notation, but not compatible with ISO8859-1. UTF-8: Because unicode does not support lantin-1, and easy to take up more space, for English letters also need two byte encoding, so that is not easy to transfer and storage, at this time UTF Code came into being, it can represent all languages and texts. However, UTF is an indefinite encoding. The length of each character ranges from 1 to 6 bytes. Generally, this encoding is used in webpages. String encoding: String ---> byte [] String decoding: byte [] ---> generation of String garbled characters: Decoding and encoding inconsistent: String ---> byte [] Decoding: byte [] ---> String garbled characters: encoding must be properly processed in the decoding and encoding inconsistent programs; otherwise, garbled characters may occur. For example, the local default encoding is GBK and the use of ISO8859-1 encoding in the program, it will appear garbled. • View the default System code: public class Demo {public static void main (String [] args) {Properties p = System. getProperties (); p. list (System. out); System. out. println (System. getProperty ("file. encoding ");} Object serialization is a way to convert an object into a binary data stream, which can facilitate object transmission or storage. If a class object needs to be serialized, its class must implement the java. io. Serializable interface. Object serialization and deserialization (Network Programming) If you input and output an object, you must use the object operation stream • ObjectInputStream: Object input stream • ObjectOutputStream: object output stream: • We call it Object serialization. If you do not want a property to be serialized, you can use transient to modify the property. • If the class is automatically static, it cannot be serialized. • If the class of a referenced field in the class does not implement Serializable, this field cannot be serialized. Use an object to operate the Stream Input serialization object process: • The JDK version must be considered for object deserialization and deserialization. We usually inject the serialVersionUID constant, the JVM will compare the serialVersionUID In the byte stream passed in with the serialVersionUID of the local corresponding class. If consistent, deserialization can be performed. Otherwise, an exception object operation stream is thrown-ObjectOutputStream is used to output objects. Common Methods: • ObjectOutputStream (OutputStream out) creates an ObjectOutputStream object written to the specified OutputStream. • Void writeObject (Object obj) Output Object. Public static void main (String [] args) {String path = "D:/obj.txt"; try (ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (path);) {oos. writeObject (new Student ("will", 99);} catch (Exception e) {e. printStackTrace () ;}} object operation stream-ObjectInputStream returns the serialized object to the deserialization. Common Methods: • ObjectInputStream (InputStream in) • Object readObject () to read objects. Public static void main (String [] args) {String path = "D:/obj.txt"; try (ObjectInputStream ois = new ObjectInputStream (new FileInputStream (path ));) {Object o = ois. readObject (); System. out. println (o);} catch (Exception e) {e. printStackTrace () ;}}: we often use WinRAR or WinZIP compressed files for convenient transmission after compression. Java provides a dedicated compression stream to compress files or folders into jar, zip, gzip, and other formats. The operations of the actually compressed stream are all in java.uti.zip. To implement zip compression in java, ZipFile, ZipOutputStream, ZipInputStream, and ZipEntry must be used. Jar and file format compressed input and output streams • jar compressed output stream: JarOutputStream • jar compressed input stream: JarInputStream • jar file: JARFile • jar entity: JarEntrygzip for File compression in unix systems, *. gz is in gzip format. • GZIP compressed output stream: GZIPOutputStream • GZIP compressed input stream: GZIPInputStreamZipEntry & ZipOutputStreamZipEntry indicates the ZIP file entry, that is, each subfile In the compressed file. • ZipEntry (String name) creates a new ZipEntry object with the specified ZipEntry name. • Boolean isDirectory () determines whether the ZipEntry is a directory. ZipOutputStream is used to compress a file or folder. • ZipOutputStream (OutputStream out) creates a new ZIP output stream • void putNextEntry (ZipEntry e) sets the ZipEntry object • void setComment (String comment) to set ZIP file comments. Example of compressing a zip File: public class ZipOutputStreamDemo {public static void main (String [] args) {File f = new File ("temp.txt "); file zf = new File ("temp.zip"); try (InputStream is = new FileInputStream (f); ZipOutputStream zos = new ZipOutputStream (new FileOutputStream (zf);) {zos. putNextEntry (new ZipEntry (f. getName (); zos. setComment ("I'm cditcast"); int len = 0; byte [] bys = new byte [1024]; while (le N = is. read (bys ))! =-1) {zos. write (bys, 0, len) ;}} catch (Exception e) {}}/ *** compressed folder ** @ author will **/public class ZipOutputStreamDemo2 {public static void main (String [] args) {File srcFile = new File ("E :\\ docs"); File destFile = new File ("E:/a.zip"); compression (srcFile, destFile );} private static void compression (File srcFile, File destFile) {try (ZipOutputStream zos = new ZipOutputStream (new FileOutputStre Am (destFile);) {zos. setComment ("I'm cditcast"); preCompression (srcFile, zos);} catch (Exception e) {e. printStackTrace () ;}} private static void preCompression (File f, ZipOutputStream zos) {if (f. isDirectory () {File [] fs = f. listFiles (); for (File file: fs) {if (file. isFile () {try (InputStream is = new FileInputStream (file);) {StringBuilder spath = new StringBuilder (); String path = f. getPa Th (). substring (f. getPath (). indexOf (File. separator) + 1); // cut off the first half of the spath. append (path ). append (File. separator ). append (file. getName (); System. out. println (spath); zos. putNextEntry (new ZipEntry (spath. toString (); int len = 0; byte [] bys = new byte [1024]; while (len = is. read (bys ))! =-1) {zos. write (bys, 0, len) ;}} catch (IOException e) {}} else {preCompression (file, zos) ;}}}} I made a test myself

Import java. io .*;
Import java. util .*;

Public class Dome {// main method
Static pipeline SC = new pipeline (System. in );
Public static void main (String [] args) throws Exception {
Neicun ();
Dayin ();
Huanchong ();
}
Public static void neicun () throws Exception {// defines the Memory Operation Flow Method
System. out. println ("test the memory operation stream below, and write the content to the memory ");
String nei = SC. next ();
InputStream input = new ByteArrayInputStream (nei. getBytes ());
OutputStream output = new ByteArrayOutputStream ();
Int I = 0;
While (I = input. read ())! =-1 ){
Output. write (Character. toUpperCase (char) I ));
}
String str = output. toString ();
Input. close ();
Output. close ();
System. out. println ("the content you just entered into the memory is" + str );
}
Private static void dayin () throws Exception {// defines the print stream method
PrintStream out = new PrintStream (new FileOutputStream (new File ("E: // wenjian" + File. separator + "text.txt ")));
System. out. println ("test the print stream below. Enter the content in the file ");
String da = SC. next ();
Out. println (da );
Out. println ("the above is your input ");
Out. close ();
System. out. printf ("You have entered the content in text.txt file in wenjian under the e-drive ");
}
Private static void huanchong () throws Exception {// defines the buffer stream method
System. out. println ("\ n has been tested to copy files in AA to BB ");
BufferedReader br = new BufferedReader (new FileReader ("E: // wenjian/AA.txt "));
BufferedWriter bw = new BufferedWriter (new FileWriter ("E: // wenjian/BB.txt "));
String line = null;
While (line = br. readLine ())! = Null ){
Bw. write (line );
Bw. newLine ();
}
Bw. close ();
Br. close ();
}
}

 

Related Article

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.