Crazy Java learning note----------Byte stream and character stream

Source: Internet
Author: User

Byte Stream and character stream

In the java.io package to manipulate the contents of the main two major categories: byte stream, character stream, two categories are divided into input and output operations. The output data in the byte stream is mainly done using outputstream , the input is InputStream, and the output in the character stream is mainly used The Writer class completes, and the input stream is primarily done using the Reader class. (These four are abstract classes)

Usage of the processing stream:


According to whether the stream is directly connected with a specific place (such as disk, memory, device, etc.), it is divided into two types: node stream and processing stream .

node Flow : You can read and write data from or to a specific place (node). such as FileReader

Processing Flow : Is the connection and encapsulation of an existing stream, which implements the data read and write through the functional invocation of the encapsulated stream.


such as BufferedReader. The construction of the process flow always takes an additional stream object to do the argument. A Stream object passes through multiple wrappers of other streams, called links to streams.

Common node streams


Parent class InputStream OutputStream Reader Writer
File *fileinputstream fileoutputstrean filereader FileWriter file to process the node stream
Array *bytearrayinputstream bytearrayoutputstream CharArrayReader chararraywriter
The stream of nodes that are processed on an array (the corresponding is no longer a file, but one in memory)
String * No StringReader StringWriter node stream for string processing
Pipeline *pipedinputstream PipedOutputStream pipedreader pipedwriter node flow for pipeline processing

Common processing flow (closing the process stream using the node stream inside the shutdown)


Parent class InputStream OutputStream Reader Writer
Buffer stream *bufferedimputstrean bufferedoutputstream bufferedreader bufferedwriter----need the parent class as the parameter construction, increase the buffering function, avoids frequently reads and writes the hard disk, The size of the buffered data can be initialized, and because of the buffering function, the flush method is required to write the data.

Convert stream *inputstreamreader outputstreamwriter-to InputStream or OutputStream as a parameter, implementing a stream of transformations from a byte stream to a character stream *datainputstream DATAOUTP Utstream-provides that the underlying data type is written to a file, or read out, why do you have this stream?

Look at this analysis, if there is no such flow, there is a long, itself only accounted for 8 bytes, if I want to write to the file, I need to convert to a string, and then into a character array, that space will occupy a lot of, but with this flow is very convenient, directly write the 8 bytes to the file is finished. is not both saving the memory space has the program to write more convenient and simple. Writing is very simple, but when reading the note, depending on the type of data read, the pointer will move down, so you have to write the order must be consistent with the order of reading to complete your correct needs.

Therefore, the typical idea when we use process flow is to wrap the byte stream with a processing stream, and the program performs the input/output function by processing the stream, allowing the byte stream to interact with the underlying I/O devices and files.

Input/output stream system:

Java's input and output streams provide nearly 40 classes: seemingly irregular, but we can divide by function: for example:

Generally speaking, the function of the byte stream is more powerful than the character stream, because all the data in the computer is binary, you know!

But I still like the character stream, straight and clear.

Convert stream

Two conversion streams:

1. Convert bytes to character stream

InputStreamReader: Convert byte input stream to character input flow, OutputStreamWriter: convert byte output stream to character output flow

2. From the character stream to the byte stream: You can get the char[] array from the character stream, convert to string, and then call the string's API function GetBytes () to get to byte[], and then you can pass Bytearrayinputstream, Bytearrayoutputstream to convert to a byte stream.

Package Com.haixu.io;import Java.io.bufferedreader;import Java.io.inputstreamreader;public class KeyinTest {public static void Main (string[] args) {try {//Convert System.in object to reader object System.out.println ("Please enter:"); InputStreamReader reader = New InputStreamReader (system.in);//Convert Reader object to BufferedReader object BufferedReader br = new BufferedReader (reader); String buffer = null;//for progressive read while (buffer = Br.readline ()) = null) {//If the read is exit, exit the program if (Buffer.equals ("Exit") { System.exit (1);} SYSTEM.OUT.PRINTLN ("Input content:" + buffer);}} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();} Finally{reader.close (); Br.close ()}//don't forget to close the stream I forgot, after joining! }}


To make something tall and still:

Pushing back the input stream

In the input and output stream, there are two special streams: Pushbackinputstream and Pushbackreader

The pushback is used for the input stream to allow bytes to be read and then returned (that is, "pushed back") to the stream. The Pushbackinputstream class implements the idea. It provides a mechanism to "peek" into what the input stream generates without being compromised.

Pushbackinputstream has two constructors: Pushbackinputstream (InputStream inputstream) Pushbackinputstream (InputStream InputStream, int numbytes) The first form creates a stream object that allows one byte to be pushed back into the input stream. The second form creates a push-back buffer stream with a numbytes length buffer. It allows multiple bytes to be pushed back into the input stream. In addition to having the same method as InputStream, Pushbackinputstream provides the unread () method, which is represented as follows: void unread (int ch) void unread (byte buffer[]) void The first form of unread (byte buffer, int offset, int numChars) pushes back the low byte of CH, which will be the next byte returned by subsequent calls to the Read () method. The second form returns the bytes in the buffer buffer. The third form pushes back the NumChars bytes starting at offset in buffer. If an attempt is made to return a byte when the push-back buffer is full, the IOException exception is raised. Java 2 makes some minor changes to Pushbackinputstream: it implements the Skip () method. Instance:
Package Com.haixu.io;import Java.io.filereader;import Java.io.pushbackreader;public class Pushbacktest {/** * push back input stream exercise * * */public static void Main (string[] args) {try {* * * * Creates an object that pushes back the input stream and sets the size of the cache to: 64 bytes * */pushbackreader PR = new Pushbackreader (New FileReader ("E://java programming//java06//src//com//haixu//io//pushbacktest.java"); char [] buf = new char[64];// String lastcontent = "" To save the last read of the strings, int hasread = 0;//Loop reads the contents of the file while ((Hasread = Pr.read (buf)) > 0) {String content = n EW string (buf, 0, hasread); int targetindex = 0;//the content of the last read is spliced with the contents of this read//To see if it contains the target string if it contains the target string if ((Targetindex = (Lastcon Tent + content). IndexOf ("New Pushbackreader") >0) {//pushes this content back into the buffer with the last content Pr.unread ((lastcontent + content). ToCharArray ()); int len = Targetindex >32? 32:targetindex;//specifies that the content of the specified length be read pr.read (buf, 0, Len);//Print Output System.out.println (new String (buf, 0, Len)); System.exit (0);} Else{system.out.println (lastcontent);//Set the contents of the last read lastcontent = Content;}}} catch (Exception e) {//Todo:handle EXCEPTIONE.PRIntstacktrace ();}}} <span style= "color: #ff0000;" ></span>

REDIRECT input and output

Java's standard input/output is represented by system.in and System.out, which, by default, represent keyboards and monitors, and when the program obtains input through the system.in, it actually gets input through the keyboard. When the program executes the output through System.out, the program is always output to the screen.

Three methods for redirecting standard input/output are provided in the system class

static void Seterr (PrintStream err) redirect "standard" error output stream

static void SetIn (InputStream in) redirect "standard" input stream

static void SetOut (PrintStream out) redirect "standard" output stream

Package Com.haixu.io;import Java.io.fileoutputstream;import Java.io.printstream;public class RedirectOut {public static void Main (string[] args) {try {* * * * * * Create PrintStream output stream */printstream PS = new PrintStream (new FileOutputStream ("ou T.text "));//redirect The standard input to the PS input stream system.setout (PS);//Enter a string System.out.println (" normal string ") to the standard;// Outputs an object System.out.println ((New Redirectout ())) to the standard output;} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();}}}


Package Com.haixu.io;import Java.io.fileinputstream;import Java.util.scanner;public class Redirectin {public static void Main (string[] args) {try {//Create FILEINPUTSTREAMD object FileInputStream fis = new FileInputStream ("E://java programming//java06// Src//com//haixu//io//redirectin.java ");//Standard input redirect to FIS input stream system.setin (FIS);// Use system.in to create a Scanner object for standard input Scanner sc = new Scanner (system.in);//Carriage return Sc.usedelimiter ("/n"); while (Sc.hasnext ()) { SYSTEM.OUT.PRINTLN ("Keyboard input content" + sc.next ());}} catch (Exception e) {//Todo:handle exceptione.printstacktrace ();}}}

Randomaccessfile

Randomaccessfile is used to access files that hold data records, you can use the Seek () method to access the records and read and write them. The sizes of these records do not have to be the same, but their size and position must be knowable. However, this class is limited to manipulating files.

Randomaccessfile does not belong to the InputStream and OutputStream class systems. In fact, in addition to implementing the Datainput and DataOutput interfaces (both DataInputStream and DataOutputStream implement both interfaces), it has nothing to do with these two classes, Do not even use any of the features that already exist in the InputStream and OutputStream classes; it is a completely independent class, and all methods (most of them belong to itself) are written from scratch. This may be because randomaccessfile can move back and forth within a file, so its behavior is fundamentally different from other I/O classes. In summary, it is a separate class that inherits directly from object.

Basically, the way Randomaccessfile works is to combine DataInputStream and dataoutputstream, plus some of its own methods, such as the getfilepointer of positioning (), The Seek () to be moved in the file, and the number of bytes to determine the length (), skipbytes () of the file size skipped. In addition, its constructor has a parameter that indicates whether to open the file as read-only ("R") or read-write ("RW") (fopen () of C). It does not support write-only files.

Only Randomaccessfile has a seek search method, and this method applies only to files. Bufferedinputstream has a mark () method that you can use to set the tag (save the result in an internal variable), and then call Reset () to return to that position, but it is too weak and not practical.

Memory-Mapped files

Memory-mapped files allow you to create and modify files that are too large to fit into memory. With a memory-mapped file, you can assume that the file has all been read into memory, and then it is accessed as a very large array. This solution greatly simplifies the code to modify the file.
Filechannel.map (Filechannel.mapmode mode, long position, long size) maps the file area of this channel directly into memory. Note that you have to indicate where it starts mapping from where the file is, how big the map is, and that is, it can also map a small fragment of a large file.


Mappedbytebuffer is a subclass of Bytebuffer, so it has all the methods of Bytebuffer, but new force () forces the contents of the buffer to be flushed to the storage device, load () loads the data from the storage device into memory, IsLoaded () The data in memory is synchronized with the storage settings. In addition to the put () and get () methods, you can easily read and write basic type data by using methods such as Ascharbuffer () to get a buffered view of the corresponding basic type of data.

/* * Program features: Demonstrates the operation of the Randomaccessfile class, while implementing a file copy operation.  */package com.lwj.demo;import java.io.*;p ublic class Randomaccessfiledemo {public static void main (string[] args) throws  Exception {randomaccessfile file = new Randomaccessfile ("File", "RW"); The following writes data to the file File.writeint (20);//4 bytes file.writedouble (8.236598);//8 bytes File.writeutf ("This is a UTF string");// This length is written at the first two bytes of the current file pointer and can be read File.writeboolean (true) by Readshort (), or 1 bytes file.writeshort (395);//2 bytes File.writelong (  2325451L);//accounted for 8 bytes File.writeutf ("Again a UTF string"); File.writefloat (35.5f);//accounted for 4 bytes file.writechar (' a ');//accounted for 2 bytes file.seek (0);//Set the position of the file pointer to the beginning of the file//below read data from file  Note the position of the file pointer System.out.println ("—————— read data from the file specified location ——————");  System.out.println (File.readint ());  System.out.println (File.readdouble ());  System.out.println (File.readutf ());  File.skipbytes (3);//Skips the file pointer over 3 bytes, skipping a Boolean and short values in this example.  System.out.println (File.readlong ()); File.skipbytes (File.readshort ()); Skips the bytes of "another UTF string" in the file, note that the Readshort () method moves the file pointer, so do notPlus 2.    System.out.println (File.readfloat ());  The following demo file copy Operation System.out.println ("—————— file to FileCopy ——————");  File.seek (0);  Randomaccessfile filecopy=new randomaccessfile ("FileCopy", "RW");  int len= (int) file.length ();//Get file Length (bytes) byte[] B=new Byte[len];  File.readfully (b);  Filecopy.write (b); System.out.println ("Copy done! "); }}


/** *  * @param skip skips how many bytes are inserted into the data * @param str to insert the string * @param fileName file path */public static void Beiju (long skip, St  Ring str, String fileName) {try {randomaccessfile RAF = new Randomaccessfile (fileName, "RW"); if (Skip <  0 | | Skip > Raf.length ()) {System.out.println ("Invalid number of skipped bytes"); return;} Byte[] B = str.getbytes (); Raf.setlength (Raf.length () + b.length); for (Long i = Raf.length ()-1; i > b.length + skip-1 ; i--) {Raf.seek (i-b.length); Byte temp = Raf.readbyte (); Raf.seek (i); Raf.writebyte (temp);} Raf.seek (skip); Raf.write (b); Raf.close ();} catch (Exception e) {e.printstacktrace ();}}


Crazy Java learning note----------Byte stream and character stream

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.