当前位置:网站首页>14.2 byte stream learning
14.2 byte stream learning
2022-07-26 12:17:00 【Wang Xiaoya】
1.IO flow
1.1 IO Flow overview and classification 【 understand 】
IO Stream Introduction
IO: Input / Output (Input/Output)
flow : It's an abstract concept , It's a general term for data transmission . In other words, the transmission of data between devices is called a stream , What is the essence of flow The data transfer
IO Stream is used to deal with data transmission between devices .
Common applications : File replication ; Upload files ; File download
IO Classification of flows
according to The flow of data
Input stream : Reading data
Output stream : Writing data
according to data type Come to share ( Default category )
Byte stream
Byte input stream
Byte output stream
Character stream
Character input stream
Character output stream
IO Stream usage scenarios
If the operation is Plain text file ( Can read ), priority of use Character stream
If it's a picture 、 video 、 Audio etc. Binary . priority of use Byte stream
If Not sure file type , priority of use Byte stream . Byte stream is a universal stream
1.2 Byte stream writes data 【 application 】
Byte stream abstract base class
InputStream: This abstract class is a superclass of all classes representing the byte input stream
OutputStream: This abstract class is the superclass of all classes representing the byte output stream
Subclass name characteristics : Subclass names are suffixes of subclass names with their parent class names
Byte output stream
FileOutputStream(String name): Create a file output stream to write to the file with the specified name
Steps to write data using byte output stream
Create byte output stream object ( Call the system function to create a file , Create byte output stream object , Let the byte output stream object point to the file )
Call the write data method of the byte output stream object
Release resources ( Close this file output stream and free any system resources associated with this stream )
Sample code
public class FileOutputStreamDemo01 { public static void main(String[] args) throws IOException { // Create byte output stream object //FileOutputStream(String name): Create a file output stream to write to the file with the specified name FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt"); /* Did three things : A: Call the system function to create a file B: Created byte output stream object C: Let the byte output stream object point to the created file */ //void write(int b): Writes the specified bytes to the output stream of this file fos.write(97); // fos.write(57); // fos.write(55); // In the end, we need to release resources //void close(): Close this file output stream and free any system resources associated with this stream . fos.close(); } }
1.3 There are three ways to write data by byte stream 【 application 】
How to write data
Method name explain void write(int b) Writes the specified bytes to the output stream of this file Write one byte of data at a time void write(byte[] b) take b.length Byte writes the output stream of this file from the specified byte array Write array data one byte at a time void write(byte[] b, int off, int len) take len Bytes start with the specified byte array , From the offset off Start writing this file output stream Write part of a byte array at a time Sample code
public class FileOutputStreamDemo02 { public static void main(String[] args) throws IOException { //FileOutputStream(String name): Create a file output stream to write to the file with the specified name FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt"); //new File(name) // FileOutputStream fos = new FileOutputStream(new File("myByteStream\\fos.txt")); //FileOutputStream(File file): Creates a file output stream to write to the File File represented by object // File file = new File("myByteStream\\fos.txt"); // FileOutputStream fos2 = new FileOutputStream(file); // FileOutputStream fos2 = new FileOutputStream(new File("myByteStream\\fos.txt")); //void write(int b): Writes the specified bytes to the output stream of this file // fos.write(97); // fos.write(98); // fos.write(99); // fos.write(100); // fos.write(101); // void write(byte[] b): take b.length Byte writes the output stream of this file from the specified byte array // byte[] bys = {97, 98, 99, 100, 101}; //byte[] getBytes(): Returns the byte array corresponding to the string byte[] bys = "abcde".getBytes(); // fos.write(bys); //void write(byte[] b, int off, int len): take len Bytes start with the specified byte array , From the offset off Start writing this file output stream // fos.write(bys,0,bys.length); fos.write(bys,1,3); // Release resources fos.close(); } }
1.4 The problem of writing two small bytes of data stream 【 application 】
How to implement line feed for byte stream write data
windows:\r\n
linux:\n
mac:\r
How to realize additional writing of byte stream write data
public FileOutputStream(String name,boolean append)
Create a file output stream to write to the file with the specified name . If the second parameter is true , Write the beginning of the byte to the end of the file instead of
Sample code
public class FileOutputStreamDemo03 { public static void main(String[] args) throws IOException { // Create byte output stream object // FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt"); FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt",true); // Writing data for (int i = 0; i < 10; i++) { fos.write("hello".getBytes()); fos.write("\r\n".getBytes()); } // Release resources fos.close(); } }
1.5 Byte stream write data and exception handling 【 application 】
Exception handling format
try-catch-finally
try{ Code with possible exception ; }catch( Exception class name Variable name ){ Exception handling code ; }finally{ Perform all cleanup operations ; }finally characteristic
finally: Provide... In exception handling finally Block to perform all cleanup operations . for instance IO Free resources in the stream
By finally The control statement must be executed , Unless JVM sign out
Sample code
public class FileOutputStreamDemo04 { public static void main(String[] args) { // Join in finally To release resources FileOutputStream fos = null; try { fos = new FileOutputStream("myByteStream\\fos.txt");// Create byte output stream object fos.write("hello".getBytes());// call write Method , Write a byte array data } catch (IOException e) { e.printStackTrace(); } finally { if(fos != null) { try { fos.close();// Released resources } catch (IOException e) { e.printStackTrace(); } } } } }
1.6 Byte stream read data ( Read one byte of data at a time )【 application 】
Byte input stream
FileInputStream(String name): Create a... By opening a connection to the actual file FileInputStream , This file is made up of pathnames in the file system name name
The steps of reading data from byte input stream
Create byte input stream object
Call the read data method of byte input stream object
Release resources
Sample code
public class FileInputStreamDemo01 { public static void main(String[] args) throws IOException { // Create byte input stream object //FileInputStream(String name) FileInputStream fis = new FileInputStream("myByteStream\\fos.txt"); int by; /* fis.read(): Reading data by=fis.read(): Assign the read data to by by != -1: Judge whether the data read is -1 */ while ((by=fis.read())!=-1) { System.out.print((char)by); } // Release resources fis.close(); } }
1.7 Byte stream copy text file 【 application 】
Case needs
hold “E:\itcast\ Inside and outside the window .txt” Copy to... In the module directory “ Inside and outside the window .txt”
Implementation steps
Copy text file , In fact, the content of a text file is read out from a file ( data source ), And then write it to another file ( Destination )
data source :
E:\itcast\ Inside and outside the window .txt --- Reading data --- InputStream --- FileInputStream
Destination :
myByteStream\ Inside and outside the window .txt --- Writing data --- OutputStream --- FileOutputStream
Code implementation
public class CopyTxtDemo { public static void main(String[] args) throws IOException { // Create a byte input stream object from the data source FileInputStream fis = new FileInputStream("E:\\itcast\\ Inside and outside the window .txt"); // Create a byte output stream object based on the destination FileOutputStream fos = new FileOutputStream("myByteStream\\ Inside and outside the window .txt"); // Read and write data , Copy text file ( Read one byte at a time , Write one byte at a time ) int by; while ((by=fis.read())!=-1) { fos.write(by); } // Release resources fos.close(); fis.close(); } }
1.8 Byte stream read data ( Read array data one byte at a time )【 application 】
A way to read an array of bytes at a time
public int read(byte[] b): Read most from input stream b.length Bytes of data
Returns the total number of bytes read into the buffer , That is, the actual number of bytes read
Sample code
public class FileInputStreamDemo02 { public static void main(String[] args) throws IOException { // Create byte input stream object FileInputStream fis = new FileInputStream("myByteStream\\fos.txt"); /* hello\r\n world\r\n for the first time :hello The second time :\r\nwor third time :ld\r\nr */ byte[] bys = new byte[1024]; //1024 And its integral multiples int len; while ((len=fis.read(bys))!=-1) { System.out.print(new String(bys,0,len)); } // Release resources fis.close(); } }
1.9 Byte stream copy image 【 application 】
Case needs
hold “E:\itcast\mn.jpg” Copy to... In the module directory “mn.jpg”
Implementation steps
Create a byte input stream object from the data source
Create a byte output stream object based on the destination
Read and write data , Copy the picture ( Read one byte array at a time , Write one byte array at a time )
Release resources
Code implementation
public class CopyJpgDemo { public static void main(String[] args) throws IOException { // Create a byte input stream object from the data source FileInputStream fis = new FileInputStream("E:\\itcast\\mn.jpg"); // Create a byte output stream object based on the destination FileOutputStream fos = new FileOutputStream("myByteStream\\mn.jpg"); // Read and write data , Copy the picture ( Read one byte array at a time , Write one byte array at a time ) byte[] bys = new byte[1024]; int len; while ((len=fis.read(bys))!=-1) { fos.write(bys,0,len); } // Release resources fos.close(); fis.close(); } }
2. Byte buffer stream
2.1 Byte buffer stream construction method 【 application 】
Byte buffer stream introduction
BufferOutputStream: This class implements buffered output streams . By setting such an output stream , Applications can write bytes to the underlying output stream , Instead of causing the underlying system to call for every byte written
BufferedInputStream: establish BufferedInputStream An internal buffer array will be created . When reading or skipping bytes from the stream , The internal buffer will be refilled from the contained input stream as needed , Many bytes at a time
Construction method :
Method name explain BufferedOutputStream(OutputStream out) Create a byte buffered output stream object BufferedInputStream(InputStream in) Create a byte buffered input stream object - Why a constructor needs a byte stream , Not a specific file or path ?
Byte buffer stream only Provide buffer , The real reading and writing data also depends on the basic byte stream object
Sample code
public class BufferStreamDemo { public static void main(String[] args) throws IOException { // Byte buffered output stream :BufferedOutputStream(OutputStream out) BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\bos.txt")); // Writing data bos.write("hello\r\n".getBytes()); bos.write("world\r\n".getBytes()); // Release resources bos.close(); // Byte buffered input stream :BufferedInputStream(InputStream in) BufferedInputStream bis = new BufferedInputStream(new FileInputStream("myByteStream\\bos.txt")); // Read one byte of data at a time // int by; // while ((by=bis.read())!=-1) { // System.out.print((char)by); // } // Read one byte array at a time byte[] bys = new byte[1024]; int len; while ((len=bis.read(bys))!=-1) { System.out.print(new String(bys,0,len)); } // Release resources bis.close(); } }
2.2 Byte stream copy video 【 application 】
Case needs
hold “E:\itcast\ Byte stream copy image .avi” Copy to... In the module directory “ Byte stream copy image .avi”
Implementation steps
Create a byte input stream object from the data source
Create a byte output stream object based on the destination
Read and write data , Copy video
Release resources
Code implementation
public class CopyAviDemo { public static void main(String[] args) throws IOException { // Record the start time long startTime = System.currentTimeMillis(); // Copy video // method1(); // method2(); // method3(); method4(); // Record the end time long endTime = System.currentTimeMillis(); System.out.println(" Total time consuming :" + (endTime - startTime) + " millisecond "); } // The byte buffer stream reads and writes one byte array at a time public static void method4() throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\ Byte stream copy image .avi")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\ Byte stream copy image .avi")); byte[] bys = new byte[1024]; int len; while ((len=bis.read(bys))!=-1) { bos.write(bys,0,len); } bos.close(); bis.close(); } // The byte buffer stream reads and writes one byte at a time public static void method3() throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\ Byte stream copy image .avi")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\ Byte stream copy image .avi")); int by; while ((by=bis.read())!=-1) { bos.write(by); } bos.close(); bis.close(); } // The basic byte stream reads and writes one byte array at a time public static void method2() throws IOException { //E:\\itcast\\ Byte stream copy image .avi // Module directory Byte stream copy image .avi FileInputStream fis = new FileInputStream("E:\\itcast\\ Byte stream copy image .avi"); FileOutputStream fos = new FileOutputStream("myByteStream\\ Byte stream copy image .avi"); byte[] bys = new byte[1024]; int len; while ((len=fis.read(bys))!=-1) { fos.write(bys,0,len); } fos.close(); fis.close(); } // The basic byte stream reads and writes one byte at a time public static void method1() throws IOException { //E:\\itcast\\ Byte stream copy image .avi // Module directory Byte stream copy image .avi FileInputStream fis = new FileInputStream("E:\\itcast\\ Byte stream copy image .avi"); FileOutputStream fos = new FileOutputStream("myByteStream\\ Byte stream copy image .avi"); int by; while ((by=fis.read())!=-1) { fos.write(by); } fos.close(); fis.close(); } }
边栏推荐
- pytest接口自动化测试框架 | 重新运行失败用例
- Use the jsonobject object in fastjason to simplify post request parameter passing
- [early knowledge of activities] list of recent activities of livevideostack
- V00 - 年纪大了,想做啥就做啥吧
- pytest接口自动化测试框架 | pytest获取执行数据、pytest禁用插件
- 网络协议:TCP/IP协议
- Li Kai: the interesting and cutting-edge audio and video industry has always attracted me
- Why is redis so fast? Redis threading model and redis multithreading
- Oracle的Windows版本能在linux中使用吗?
- 基于STM32的SIM900A发送中文和英文短信
猜你喜欢

FPGA入门学习(二) - 二选一的选择器

Dry goods semantic web, Web3.0, Web3, metauniverse, these concepts are still confused? (medium)

CVPR 2022 new SOTA for monocular depth estimation new CRFs: neural window fullyconnected CRFs

【Map】万能的Map使用方法 & 模糊查询的两种方式

面试京东T5,被按在地上摩擦,鬼知道我经历了什么?

Is it easy to find a job after programmer training?

Jsj-3/ac220v time relay

Introduction to FPGA (II) - one out of two selector

儿童玩乐场所如何运营?

海外APP推送(下篇):海外厂商通道集成指南
随机推荐
Network protocol: tcp/ip protocol
数智转型,管理先行|JNPF全力打造“全生命周期管理”平台
MATLAB中strjoin函数使用
Use and optimization of MySQL composite index (multi column index)
pytest接口自动化测试框架 | pytest配置文件
Pytest interface automated testing framework | introduction to fixture of pytest
Is it easy to find a job after programmer training?
腾讯云与智慧产业事业群(CSIG)调整组织架构,成立数字孪生产品部
V01 - XX,记录美好生活从日志开始
Flutter's learning path
Redis实现Single单点登入详解
Pytest interface automation test framework | pytest configuration file
Introduction to FPGA (II) - one out of two selector
Pytoch deep learning quick start tutorial -- mound tutorial notes (II)
请问下有人知道FlinkSQL 的 Retrack 在哪里可以指定吗? 网上资料只看到API 代码设
.NET WebAPI 使用 GroupName 对 Controller 分组呈现 Swagger UI
尤雨溪向初学者推荐Vite 【为什么使用Vite】
DS-112时间继电器
Ds-24c/dc220v time relay
二、容器_