InputStream and OutputStream and related knowledge summary

https://www.jianshu.com/p/e5bc7ea5f948

 

Sister recently helped write the reptile when it came to strange question, the same program can be run properly and returns results in an error on Windows on a Mac, and finally by the investigation found that different Linux and Windows default encoding, and their program is not set the encoding automatically uses the default encoding, resulting in an error. After trying a variety of encoding were unsuccessful, and finally found the cause because of his knowledge of the input and output streams are not in place, not properly used, it sort of learning.

First, know what a byte stream and character stream. Input and output program is stored in the form of stream, stored byte stream file is full. The type of data processing can be divided into a byte stream and a stream of characters. Byte stream is the basis of character streams.

Byte stream: a byte stream processing unit is a byte, byte and byte array operation. If it is audio, pictures, etc. recommended by the stream of bytes.
Character stream: character stream processing unit is a two-byte UNICODE characters, character house operation, an array of characters and a string of multi-national language support is better, if it is recommended to use a text character stream.

Stream-based byte stream: OutputStream usually ending and InputStream, DataOutputStream, DataInputStream, FileOutputStream ......
** Based on Stream character stream: usually ends Writer and Reader, PrintWriter, FileWriter, FileReader, StringWriter ......

Can be found in the vast majority of streams are paired, including input and output streams. Such input and output streams can be appreciated that
the input stream (InputStream and Reader) can be seen as a water faucet, the water outflow has a function, namely a function of generating program data, read it corresponds to the open switch, then it would effluent stream (data) .
Output stream (OutputStream and Writer) can be seen as a water faucet, having a function of storing water, i.e. generated data receiving program, write the equivalent of the open switch, water (data) flows into the tap water.
Introduced over the basic concept, and now look at the basic usage.

InputStream  
Reading data from the stream  
public abstract int read() throws IOException The next byte read from the input stream. Return 0 to 255 int the range of byte values. If the end of the stream has been reached because no byte is available, it returns -1.
public int read(byte[] b) throws IOException Some number of bytes read from the input stream, and stores it in the buffer array b. It returns the number of bytes actually read as an integer. Equivalent to read (byte [], int, int)
public int read(byte[] b, int off, int len) throws IOException The input stream up to len bytes of data is read into the byte array. Attempts to read len bytes, bytes read but also may be less. The read elements stored in the first byte of the element b [off] to b [off + k-1] is, and so on.
public long skip(long n) throws IOException Skip and discards n bytes of input data streams. For various reasons, the number of bytes to skip at the end may be less than the number of skip method may also be zero. The reasons for this are many, already before reaching the end of file n bytes skipped is only one possibility. Returns the actual number of bytes skipped. If n is negative, no bytes are skipped. skip method of creating such a byte array and then repeatedly reads bytes therein until n bytes read enough or reaches the end of the stream. This method is recommended subclass provides a more efficient implementation. For example, implementation-dependent search capabilities.
public int available() throws IOException Returns a stream input method calls without blocking the estimated input byte stream read (or skipped) (number of bytes of the stream has not been read). The next call may be the same thread, it may be another thread. This estimate a read or skip a number of bytes not block, but the number of bytes read or less than this number may be skipped. Note that to achieve some InputStream will return the total number of bytes in the stream, but many do not realize. I try to use this method's return value to allocate a buffer to hold all this data flow approach is incorrect. If you have to call close () method closes this input stream, then the sub-class implementation of this method may choose to throw IOException. The available method of InputStream class always returns 0. This method should be overridden by subclasses.
Close flow  
public void close() throws IOException Close the input stream and releases associated with the flow of all system resources
Tag using the input stream  
public void mark(int readlimit) It marks the current position in this input stream. Subsequent calls will reset method reposition this stream at the last marked for subsequent re-read to read the same byte. readlimit parameter indicates the number of bytes read readmit failure flag.
public void reset() throws IOException The read pointer is again points to the location of the recording mark method.
public boolean markSupported() Tests if this input stream supports the mark () and reset () method.
OutputStream  
输出数据  
public abstract void write(int b) throws IOException 将指定的字节写入输出流。write 的常规协定是:向输出流写入一个字节。要写入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。
public void write(byte[] b) throws IOException 将b.length个字节从指定的byte数组写入此输出流。与write(b, 0, b.length)等同
public void write(byte[] b, int off, int len) throws IOException 将指定数组中从偏移量off开始的len个字节写入此输出流。
刷新流  
public void flush() throws IOException 刷新此输出流并强制写出所有缓冲的字节。如果此流的预期目标是由基础操作系统提供的一个抽象(如一个文件),则刷新此流只能保证将以前写入到流的字节传递给操作系统进行写入,但不保证能将这些字节实际写入到物理设备(如磁盘驱动器)。
关闭流  
public void close() throws IOException 关闭此输出流并释放与此流有关的所有系统资源

通过输入输出流复制图片的例子:

public class Test {
    public static void main(String[] args) throws IOException{ long startTime = System.currentTimeMillis(); InputStream is = new FileInputStream(new File("/Users/zhaokang/Desktop/1.jpg")); OutputStream os = new FileOutputStream(new File("/Users/zhaokang/Desktop/2.jpg")); int i = 0; while(i != -1){ i = is.read(); os.write(i); } is.close(); os.close(); long endTime = System.currentTimeMillis(); System.out.println("程序运行时间:"+(endTime-startTime)+"ms"); } } //输出结果为:程序运行时间40231ms 

通过缓冲流提高复制速度

public class Test {
    public static void main(String[] args) throws IOException{ long startTime = System.currentTimeMillis(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("/Users/zhaokang/Desktop/1.jpg"))); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("/Users/zhaokang/Desktop/2.jpg"))); int i = 0; while(i != -1){ i = bis.read(); bos.write(i); } bos.flush(); bis.close(); bos.close(); long endTime = System.currentTimeMillis(); System.out.println("程序运行时间:"+(endTime-startTime)+"ms"); } } //输出结果为:程序运行时间486ms 

文件较大时,做一个缓冲处理

public class Test {
    public static void main(String[] args) throws IOException{ long startTime = System.currentTimeMillis(); byte[] tmp = new byte[1024]; InputStream is = new FileInputStream(new File("/Users/zhaokang/Desktop/1.jpg")); OutputStream os = new FileOutputStream(new File("/Users/zhaokang/Desktop/2.jpg")); int i = 0; while(i != -1){ i = is.read(tmp); os.write(tmp); } is.close(); os.close(); long endTime = System.currentTimeMillis(); System.out.println("程序运行时间:"+(endTime-startTime)+"ms"); } } //输出结果为:程序运行时间61ms 

双缓冲

public class Test {
    public static void main(String[] args) throws IOException{ long startTime = System.currentTimeMillis(); byte[] tmp = new byte[1024]; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("/Users/zhaokang/Desktop/1.jpg"))); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("/Users/zhaokang/Desktop/2.jpg"))); int i = 0; while(i != -1){ i = bis.read(tmp); bos.write(tmp); } bos.flush(); bis.close(); bos.close(); long endTime = System.currentTimeMillis(); System.out.println("程序运行时间:"+(endTime-startTime)+"ms"); } } //输出结果为:程序运行时间29ms 

可以看到第一种情况效率最低,所以若非特殊要求可以放弃这种方法。

Guess you like

Origin www.cnblogs.com/yycc/p/11647568.html
Recommended