Home >Java >Javagetting Started >How to classify IO streams in java
1. IO: upload and download, write and write
Stream: a series of flowing data, flowing in a first-in, first-out manner , pipeline, program-centered, program and network | file | server | array.. (Related course recommendations: java video tutorial)
Classification
1) According to the flow direction:
input stream; output stream
2) Operation unit classification:
Byte stream (universal stream): any content can be transferred It is bytes and can transmit text, pictures, and audio; character stream: can only operate plain text data
3) According to function:
Node stream: wraps the source to realize basic functions; function stream : Enhance the performance of node streams and improve efficiency
4) Each classification is complementary
Byte stream
(1) Bytes Input stream: InputStream This abstract class is the superclass of all classes that represent byte input streams; FileInputStream obtains input bytes from a file in the file system
//字节流输入 InputStream //导包 导包快捷键: ctrl+shift+o import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class Demo01 { public static void main(String[] args) throws IOException { //FileInputStream(String name) 通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定 //FileInputStream(File file) 通过打开一个到实际文件的连接来创建一个 FileInputStream, 该文件通过文件系统中的 File 对象 file 指定 InputStream is=new FileInputStream(new File("D:/test.txt"));//创建D盘符的根目录下的文件 System.out.println(is); //方式1: int read() 读入数据 一个字节一个字节读入 /*int num=is.read(); System.out.println((char)num); num=is.read(); System.out.println((char)num); System.out.println((char)(is.read()));*/ //方式2:使用循环,循环读入,可以简化代码,重复代码只写一次,但还是一个字节一个字节的读入 /*int num=-1; while((num=is.read())!=-1){ System.out.println((char)num); }*/ //方式3:int read(byte[] b) 一个字节数组一个字节数组的读入 //返回值: 返回读入到字节数组中数据的个数,没有读到返回-1 byte[] car=new byte[1]; //int len=is.read(car); int len=-1; while((len=is.read(car))!=-1){ System.out.println(new String(car,0,len)); } //关闭 is.close(); } }
(2) Byte output stream: OutputStream This abstract class is the superclass of all classes that represent output byte streams; FileOutputStream The file output stream is the output stream used to write data to File
//字节输出流 OutputStream //导包 导包快捷键: ctrl+shift+o import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class Demo02 { public static void main(String[] args) { //FileOutputStream(String name)创建一个向具有指定名称的文件中写入数据的输出文件流 //FileOutputStream(String name,boolean append) 创建一个向具有指定 name 的文件中写入数据的输出文件流 //FileOutputStream(File file,boolean append) 创建一个向指定 File 对象表示的文件中写入数据的文件输出流 //boolean append 返回值:true追加,false不追加(默认false) OutputStream os=null; //try...catch(){} 捕捉异常,处理异常 try { //1.选择流 os=new FileOutputStream("D:/hhh.txt",hhtrue); //文件不存在,系统会自动帮我们创建,但文件夹不会 //2.准备数据 String str="要好好学习,天天向上..."; byte[] c和=str.getBytes(); //3.写出 void write(byte[] b) os.write(ch); //4.刷出 os.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ //5.关闭 try {//预防空指针异常 if(os!=null){ os.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
Character stream
Can only operate plain text
1) Node stream:
(1)Character input stream: Reader is an abstract class for reading character streams; FileReader is a convenience class for reading character files
//字符输入流 Reader //导包 导包快捷键: ctrl+shift+o import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; public class Demo03 { public static void main(String[] args) { //FileReader(String fileName) Reader rd=null; try { //1.选择流 rd=new FileReader("D:/hehe.txt");//创建D盘符的根目录下的文件 //2.读入 //方法1:int read() 读取单个字符。 /*System.out.println((char)rd.read()); System.out.println((char)rd.read()); System.out.println((char)rd.read()); System.out.println((char)rd.read());*/ int len=-1; //存储读到的数据 如果为-1,证明已达到末尾 //方法2: /*while(-1!=(len=rd.read())){ System.out.println((char)len); }*/ //方法3:int read(char[] cbuf) 将字符读入数组。 char[] car=new char[1024]; while((len=rd.read(car))!=-1){ System.out.println(new String(car,0,len)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ if(rd!=null){ try { //关闭功能 rd.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
(2)Character output stream: Writer is an abstract class for writing character streams; FileWriter is a convenient class for writing character files
//字符输出流:Writer //导包 导包快捷键: ctrl+shift+o import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; public class CharDemo02 { public static void main(String[] args) { //FileWriter(File file) //默认不追加 //FileWriter(File file, boolean append) //FileWriter(String file) //FileWriter(String file, boolean append) Writer rt=null; try { //1.选择流 rt=new FileWriter("D:/houhou.txt",true); //2.写出 /* void write(char[] cbuf) 写入字符数组 void write(char[] cbuf, int off, int len) 写入字符数组的某一部分 void write(int c) 写入单个字符 void write(String str) 写入字符串 void write(String str, int off, int len) 写入字符串的某一部分 */ rt.write(97); rt.write("\r\n"); //换行 rt.write("你真好看!!!!"); rt.write("\r\n"); rt.write("你真好看!!!!",2,2); rt.write("\r\n"); char[] ch={'a','b','c','d','e'}; rt.write(ch); rt.write("\r\n"); rt.write(ch,2,3); //3.刷出 rt.flush(); } catch (IOException e) { e.printStackTrace(); } finally{ //4.关闭 if(null!=rt){ try { rt.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Functional flow
Buffered stream: Enhanced functions, improved performance, faster reading and writing efficiency
1) Byte stream:
BufferedInputStream Byte input stream buffered stream
BufferedOutputStream byte output stream buffered stream
There is no new method, polymorphic use can occur
//导包 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class BufferedInputStream01 { public static void main(String[] args) throws IOException { //1.选择流 //BufferedInputStream(InputStream in) InputStream is=new BufferedInputStream(new FileInputStream("D:/hehe.txt")); OutputStream os=new BufferedOutputStream(new FileOutputStream("E:/hengheng.txt") ); //2.读写 byte[] car=new byte[1024]; int len=-1; while((len=is.read(car))!=-1){ os.write(car,0,len); } //3.刷出 os.flush(); //4.关闭 os.close(); is.close(); } }
2) Character stream:
BufferedReader Character input stream buffered stream
New method: String readLine() reads a text line
BufferedWriter character output stream buffer stream
New method: void newLine() writes a line delimiter
//导包 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class BufferedReader02 { public static void main(String[] args) throws IOException { //1.选择流 导包快捷键: ctrl+shift+o BufferedReader br=new BufferedReader(new FileReader("D:/hehe.txt")); BufferedWriter bw=new BufferedWriter(new FileWriter("D:/ccc.txt")); //2.读写 String msg=null; while((msg=br.readLine())!=null){ bw.write(msg); bw.newLine(); } //3.刷出 bw.flush(); //4.关闭 bw.close(); br.close(); } }
Data stream (byte node stream)
Data stream (byte node stream):
Read and write basic data type String type data, It is a kind of byte stream function stream
DataInputStream new method: readXxx()
DataOutputStream new method: writeXxx()
Multiple occurrences cannot occur if there is a new method state, write first and then write
Possible exceptions encountered: EOFException The file has, the content cannot be read, the written source file must be read
//导包 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Data01 { public static void main(String[] args) throws IOException { //调用方法 write("D:/data.txt"); read("D:/data1.txt"); } //读入 public static void read(String path) throws IOException{ //1.输入流 数据类型+数据 DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream(path))); //2.读入 int i=in.readInt(); boolean b=in.readBoolean(); String s=in.readUTF(); System.out.println(i+"-->"+b+"-->"+s); //3.关闭 in.close(); } //写出 public static void write(String path) throws IOException{ //1.输出流 DataOutputStream out=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(path))); //2.准备数据 int i=101; boolean f=false; String s="哈哈"; //3.写出 写出和读入的顺序要保持一致 out.writeInt(i); out.writeBoolean(f); out.writeUTF(s); //4.刷出 out.flush(); //5.关闭 out.close(); } }
Object stream
Object saves data type data
Byte function stream: When you want to transmit | read and write object type data, you can use an object stream
Serialization: The process of converting object type data into a storable | transmittable state
ObjectInputStream() Deserialized input stream New method: readObject()
ObjectOutputStream( ) Serialized output stream New method: writeObject()
Note:
1) Serialize first and then deserialize
2) Serialize and deserialize the reading and writing order Consistent
3) Not all classes can be serialized java.io.Serializable empty interface
4) Not all properties need to be serialized transient
5)static Content will not be serialized
6) If the parent class implements the Serializable interface, all content can be serialized in the subclass
If the subclass implements the Serializable interface, but the parent class does not implement it, the subclass Only content unique to subclasses can be serialized
//导包 import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; public class ObjectDemo02 { public static void main(String[] args) throws IOException, ClassNotFoundException { write("D:/object.txt"); read("D:/object.txt"); } //反序列化输入 public static void read(String path) throws IOException, ClassNotFoundException{ //1.输入流 ObjectInputStream is=new ObjectInputStream(new BufferedInputStream(new FileInputStream(path))); //2.读入 Object p= is.readObject(); int[] arr= (int[]) is.readObject(); if(p instanceof Person){ Person person=(Person)p; System.out.println(person.getName()); } System.out.println(p); System.out.println(Arrays.toString(arr)); //3,关闭 is.close(); } //序列化输出 public static void write(String path) throws IOException{ //1.输出对象信息 ObjectOutputStream os=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path))); //2.准备数据 Person p=new Person("aaa",18); int[] arr={1,2,3,4}; //3.输出 os.writeObject(p); os.writeObject(arr); //4.刷出 os.flush(); //5.关闭 os.close(); } } //接口 class Person implements Serializable{ private String name; private static int age; public Person() { } public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
2. File class
File class: abstract representation of file and directory path names
Functions provided: The ability to operate outside the file, but not the content inside the file
Can define the real path | file, and it can also be defined if it is not there, so the abstract expression is
Constructor : File(File parent, String child) Creates a new File instance based on the parent abstract pathname and child pathname string
File(String pathname) Created by converting the given pathname string to an abstract pathname A new File instance
File(String parent, String child) Create a new File instance based on the parent path name string and the child path name string
This article comes from java introductory tutorial column, welcome to learn!
The above is the detailed content of How to classify IO streams in java. For more information, please follow other related articles on the PHP Chinese website!