difference between byte stream and character stream

Source: Internet
Author: User

Article transferred from http://blog.csdn.net/zxman660/article/details/7875799

Byte Stream and character stream

First look at a nasty concept:

All the data in the program is transmitted or saved in a stream, and the program needs the data to read the data using the input stream, and when the program needs to save some data, it will use the output stream to complete.

The input and output in the program is saved as a stream, and the actual bytes stored in the stream are all byte files.

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. Output data in the byte stream is mainly done using OutputStream, the input is InputStream, the output in the character stream is mainly done using the writer class, and the input stream is mainly done using reader class. (These four are abstract classes)

The package java.io, which is dedicated to the input and output functions, is available in Java, including:
Inputstream,outputstream,reader,writer
InputStream and OutputStream, two are designed for byte streams, primarily for processing bytes or binary objects,
Reader and Writer. Two are designed for character streams (two bytes in a character) and are primarily used to handle characters or strings.


A character stream processes a cell that is 2-byte Unicode characters, manipulating characters, character arrays, or strings, and a byte-stream processing unit of 1 bytes, manipulating bytes and byte arrays. So a character stream is a character that is converted from a Java virtual machine to a 2-byte Unicode character, so it's better for multi-language support! If it is audio files, pictures, songs, use a word throttle better, if it is related to Chinese (text), with a character stream better
All of the files are stored in byte (byte) storage, and the characters that are not files on the disk are encoded into bytes, and then the bytes are stored to disk. When reading a file (especially a text file), it is also a byte-by-byte read to form a sequence of bytes

Byte streams can be used for any type of object, including binary objects, whereas character streams only handle characters or strings; 2. Byte stream provides the ability to handle any type of IO operation, but it cannot handle Unicode characters directly, and a character stream can
Byte stream is the most basic, all the Inputstrem and OutputStream subclasses are, mainly used in processing binary data, it is processed by byte, but in fact, a lot of data is text, and put forward the concept of character stream, it is the virtual machine encode to deal with, That is, the conversion of the character set is related by Inputstreamreader,outputstreamwriter, in fact through byte[] and string. The problem of Chinese characters appearing in the actual development is actually caused by the transformation of the character stream and the byte stream.

================== we can also see: ============
The read () method of the Reader class returns the type int: The character read as an integer (two bytes total 16 bits), the range is between 0 and 65535 (0X00-0XFFFF), and returns 1 if the end of the stream has been reached.


The read () of InputStream also returns int, but since this class is byte-oriented and has 8 bits for one bytes, it returns an int byte value in the range of 0 to 255 . If no bytes are available since the end of the stream has been reached, the return value-1. So for values that cannot be represented by 0-255, a character stream is used to read it! such as Chinese characters.

Operation Flow

In Java, the IO operation also has the corresponding steps, take the file operation as an example, the main operation flow is as follows:

1 opening a file using the file class

2 Specify the location of the output by a subclass of Byte stream or character stream

3 for read/write operations

4 off input/output

IO operation is a resource operation, always remember to close

BYTE stream

Byte stream is mainly the operation of type data, byte array, the main operation class is OutputStream, InputStream

BYTE output stream: OutputStream

OutputStream is the largest parent of the byte output stream in the entire IO package, as defined in this class:

Public abstract class OutputStream extends Object implements Closeable,flushable

As you can see from the above definition, this class is an abstract class, and if you want to use this class, you first have to instantiate the object through a subclass, so if you are working on a file now, you can use the: FileOutputStream class. After you have transformed up, you can instantiate the OutputStream

Closeable represents an operation that can be closed, because the program runs to the end and is sure to close

Flushable: Indicates refresh, emptying of in-memory data

The FileOutputStream class is constructed as follows:

Public fileoutputstream (file file) throws FileNotFoundException

Write Data:

1 Import java.io.File;
2 Import Java.io.FileOutputStream;
3 Import java.io.IOException;
4 Import Java.io.OutputStream;
5
6 public class Test11 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 OutputStream out=new FileOutputStream (f);//If the file does not exist, it will be created automatically
Ten String str= "Hello World";
Byte[] B=str.getbytes ();
Out.write (b);//Because it is a byte stream, it is converted to an array of bytes for output
Out.close ();
14}
15}

You can also output one byte at a byte, as follows:

1 Import java.io.File;
2 Import Java.io.FileOutputStream;
3 Import java.io.IOException;
4 Import Java.io.OutputStream;
5
6 public class Test11 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 OutputStream out=new FileOutputStream (f);//If the file does not exist, it will be created automatically
Ten String str= "Hello World";
Byte[] B=str.getbytes ();
(int i=0;i<b.length;i++) {
Out.write (B[i]);
14}
Out.close ();
16}
17}

The above output will only overwrite, and if you want to append, look at another way to construct the FileOutputStream class:

Public FileOutputStream (File File,boolean append) throws FileNotFoundException

In the construction method, if the value of append is set to True, the content is appended to the end of the file.

1 Import java.io.File;
2 Import Java.io.FileOutputStream;
3 Import java.io.IOException;
4 Import Java.io.OutputStream;
5
6 public class Test11 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 OutputStream out=new FileOutputStream (f,true);//Append Content
Ten String str= "\r\nhello World";
Byte[] B=str.getbytes ();
(int i=0;i<b.length;i++) {
Out.write (B[i]);
14}
Out.close ();
16}
17}

Change behavior in file: \ r \ n

BYTE input stream: InputStream

Now that the program can write to the file, you can read the content from the file by InputStream, first of all, the definition of the InputStream class:

Public abstract class InputStream extends Object implements Closeable

Like the OutputStream class, the InputStream itself is an abstract class that must rely on its subclasses, and if it is read from a file, it is implemented using FileInputStream.

Observe the construction method of the FileInputStream class:

Public fileinputstream (file file) throws FileNotFoundException

Read the file:

1 Import java.io.File;
2 Import Java.io.FileInputStream;
3 Import java.io.IOException;
4 Import Java.io.InputStream;
5
6 public class Test12 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 InputStream in=new FileInputStream (f);
Ten byte[] b=new byte[1024];
one int len=in.read (b);
In.close ();
System.out.println (New String (B,0,len));
14}
15}

But the above method is problematic, with no need to open up such a large byte array, it is obviously wasteful, we can according to the size of the file to define the size of the byte array, the method in the file class: public long Length ()

1 Import java.io.File;
2 Import Java.io.FileInputStream;
3 Import java.io.IOException;
4 Import Java.io.InputStream;
5
6 public class Test13 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 InputStream in=new FileInputStream (f);
Byte[] b=new byte[(int) f.length ()];
In.read (b);
In.close ();
System.out.println (New String (b));
14}
15}

We change the way, one byte a byte read into ~

1 Import java.io.File;
2 Import Java.io.FileInputStream;
3 Import java.io.IOException;
4 Import Java.io.InputStream;
5
6 public class Test14 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 InputStream in=new FileInputStream (f);
Byte[] b=new byte[(int) f.length ()];
one for (int i=0;i<b.length;i++) {
B[i]= (Byte) in.read ();
13}
In.close ();
System.out.println (New String (b));
16}
17}

However, the above situation is only suitable to know the size of the input file, do not know the following methods:

1 Import java.io.File;
2 Import Java.io.FileInputStream;
3 Import java.io.IOException;
4 Import Java.io.InputStream;
5
6 public class Test15 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 InputStream in=new FileInputStream (f);
Ten byte[] b=new byte[1024];
int temp=0;
len=0 int;
while ((Temp=in.read ())!=-1) {//-1 marks the end of a file read
b[len]= (byte) temp;
len++;
16}
In.close ();
System.out.println (New String (B,0,len));
19}
20}


Character Stream

In a program where a character equals two bytes, Java provides reader, writer two classes that specialize in character streams.


Character output stream: Writer

Writer itself is the output class of a character stream, and this class is defined as follows:

Public abstract class Writer extends Object implements Appendable,closeable,flushable

This class is itself an abstract class, and if you want to use this class, you must use its subclasses, and if you are writing to a file, you should use the FileWriter subclass.

The construction method of the FileWriter class is defined as follows:

Public FileWriter (file file) throws IOException

The operation of the character stream is better than the byte stream operation, it is possible to output the string directly, no longer as before the conversion operation.

Write file:

1 Import java.io.File;
2 Import Java.io.FileWriter;
3 Import java.io.IOException;
4 Import Java.io.Writer;
5
6 public class Test16 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 Writer out=new FileWriter (f);
Ten String str= "Hello World";
Out.write (str);
Out.close ();
13}
14}

By default, the output is overwritten again, and the appended method is appended to the constructor.

1 Import java.io.File;
2 Import Java.io.FileWriter;
3 Import java.io.IOException;
4 Import Java.io.Writer;
5
6 public class Test17 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 Writer out=new FileWriter (f,true);//Append
Ten String str= "\r\nhello World";
Out.write (str);
Out.close ();
13}
14}


Character input stream: Reader

Reader uses characters to extract data from a file, and the reader class is defined as follows:

Public abstract class Reader extends Objects implements Readable,closeable

Reader itself is an abstract class, and if you want to read the contents from a file now, you can use the FileReader subclass directly.

The construction method of the FileReader is defined as follows:

Public filereader (file file) throws FileNotFoundException

Reads the data as a character array:

1 Import java.io.File;
2 Import Java.io.FileReader;
3 Import java.io.IOException;
4 Import Java.io.Reader;
5
6 public class Test18 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 Reader input=new FileReader (f);
Ten char[] c=new char[1024];
one int len=input.read (c);
Input.close ();
System.out.println (New String (C,0,len));
14}
15}

You can also use a circular method to determine whether to read the end:

1 Import java.io.File;
2 Import Java.io.FileReader;
3 Import java.io.IOException;
4 Import Java.io.Reader;
5
6 public class Test19 {
7 public static void Main (string[] args) throws IOException {
8 file F = new file ("D:" + file.separator+ "test.txt");
9 Reader input=new FileReader (f);
Ten char[] c=new char[1024];
int temp=0;
len=0 int;
while ((Temp=input.read ())!=-1) {
c[len]= (char) temp;
len++;
16}
Input.close ();
System.out.println (New String (C,0,len));
19}
20}

The difference between a byte stream and a character stream

The byte stream is very similar to the use of character streams, so what is the difference between the operation code and the other?

Byte stream in the operation of the time itself is not used in the buffer (memory), and the file itself is directly manipulated, and the character stream is used in the operation of the buffer

Byte stream when manipulating a file, the file can output even if the resource is not closed (the Close method), but if the character stream does not use the Close method, nothing is output, the character stream is buffered, and the flush method can be used to force the flush buffer. Then you can output the content without close.

In the development of the use of the word throttle or use character flow good?

When you save files on all your hard disks or transfer them in a byte-by-byte manner, including the picture is done in bytes, and the characters are only formed in memory, so the use of bytes is the most.

If you want a Java program to implement a copy function, you should use the byte stream to operate (possibly copying the picture), and to use the side-read-write Method (save memory).

difference between 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.