- The Java language uses a stream mechanism to implement input/output. The so-called stream is the orderly arrangement of data. The stream can come from a certain source (called the Source of Stream) to a certain destination (called the Sink of Stream).
- Classification of flow:
- Flow direction points: input flow, output flow
- Stream source points: character stream, byte stream
- Function points: node flow, processing flow
- Hierarchical structure of InputStream and OutoutStream
- The hierarchical structure of Reader and Writer
1. Object flow
ObjectInputStream and ObjectOutputStream
case: save the object to the file through the object stream, and then read the content in the file through the object stream
- Save the object to the file must implement the Serializable serialization interface
package com.cao.demo.lesson01;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Test {
/**
* 保存(写入)
*/
public void saveObj2File() {
int num = 10;
String word = "cao";
User user = new User();
user.setName(word);
user.setAge(num);
//创建流
FileOutputStream fo = null;
ObjectOutputStream oo = null;
try {
fo = new FileOutputStream("C:\\iweb\\1.dat");
oo = new ObjectOutputStream(fo);
//写入
oo.writeInt(num);
oo.writeUTF(word);
oo.writeObject(user);
//刷新缓冲区
oo.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fo != null) {
fo.close();
}
if (oo != null) {
oo.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 读取
*/
public void readObjFromFile() {
FileInputStream fi = null;
ObjectInputStream oi = null;
try {
//创建流
fi = new FileInputStream("C:\\iweb\\1.dat");
oi = new ObjectInputStream(fi);
//读取
int num = oi.readInt();
String word = oi.readUTF();
//强制类型转换
User user = (User) oi.readObject();
//输出
System.out.println(num);
System.out.println(word);
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fi != null) {
fi.close();
}
if (oi != null) {
oi.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test test = new Test();
test.saveObj2File();
test.readObjFromFile();
}
}
Example class:
package com.cao.demo.lesson01;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID=100;
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
result:
C:\Java\jdk1.8.0_181\bin\java.exe...
10
cao
User{
name='cao', age=10}
Process finished with exit code 0
2. Byte array stream
ByteArrayInputStream 和 ByteArrayOutputStream
ByteArrayInputStream
Contains an internal buffer that contains the bytes read from the stream. It isByteArrayInputStream
invalid to close . The methods in
ByteArrayOutputStream
this class can be called after closing; this class implements an output stream in which the data is written A byte array. The buffer will automatically grow as data is continuously written . UsetoByteArray()
andtoString()
obtain the data.ByteArrayOutputStream
Close is invalid . The methods in this class can still be called after the stream is closed.
package com.cao.demo.lesson02;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws IOException {
String word = "hello!";
// 将要存放的数据转成字节数组
byte[] buf = word.getBytes();
// 将字节数组的内容保存到缓冲区
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buf);
int code;
// 每次读取一个字节对应的 unicode 码
while ((code = byteArrayInputStream.read()) != -1) {
System.out.println(code + "->" + (char) code);
}
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
byteArrayOutputStream.write(101);
byteArrayOutputStream.write(102);
byteArrayOutputStream.write('\n');
byteArrayOutputStream.write("abc".getBytes());
byteArrayOutputStream.write('\n');
byte[] a={
111,111,111};
byteArrayOutputStream.write(a);
// 获取字节数组流中的内容
// 字符的可以通过 toString 方法获取内容
System.out.println(byteArrayOutputStream.toString());
// 字节的 toByteArray 获取一个字节数组
System.out.println(Arrays.toString(byteArrayOutputStream.toByteArray()));
}
}
104->h
101->e
108->l
108->l
111->o
33->!
ef
abc
ooo
[101, 102, 10, 97, 98, 99, 10, 111, 111, 111]
3、PrintWriter
package com.cao.demo.lesson03;
import java.io.File;
import java.io.PrintWriter;
public class Test {
public static void main(String[] args) {
File file = new File("C:\\iweb\\Test.txt");
PrintWriter printWriter=null;
try{
printWriter=new PrintWriter(file);
printWriter.println("hello word");
// printWriter.write(".....");
printWriter.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
if(printWriter!=null){
printWriter.close();
}
}
}
}
4、
InputStreamReader 和 OutputStreamWriter:
- InputStreamReader is a bridge from byte flow to character stream, and OutputStreamWriter is a bridge from character flow to byte stream.
package com.cao.demo.lesson04;
import java.io.*;
import java.nio.charset.Charset;
public class Test {
public static void main(String[] args) throws IOException {
String src = "C:\\iweb\\Test.txt";
FileReader fileReader = new FileReader(src);
char[] buffer = new char[8];
int len;
while ((len = fileReader.read(buffer)) != -1) {
System.out.println(new String(buffer));
}
fileReader.close();
System.out.println("------------------------");
/**
* 使用InputStreamReader
*/
// 按照字节读取
FileInputStream fileInputStream = new FileInputStream(src);
// 转换流 将字节流转成了字符流 指定编码
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, Charset.forName("GBK"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
fileInputStream.close();
inputStreamReader.close();
bufferedReader.close();
}
}
hellohel
lohellol
------------------------
hellohellohello
5. Read the stream via URL
URL class: represents a uniform resource locator , which is a pointer to Internet "resources".
package com.cao.demo.lesson05;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.*;
public class Test {
public static void main(String[] args) throws Exception {
String src="http://qqpublic.qpic.cn/qq_public/0/0-3132403110-66C8E88CD7AEE27765F60FC87ED769F9/0?fmt=gif&size=5093&h=490&w=490&ppv=1";
URI uri=new URI(src);
URL url=uri.toURL();
// String path=url.getPath();
// System.out.println(path);
// System.out.println(url.getFile());
URLConnection urlConnection=url.openConnection();
InputStream inputStream=urlConnection.getInputStream();
FileOutputStream fileOutputStream=new FileOutputStream("C:\\iweb\\王冰冰.gif");
byte[] buff=new byte[1024];
int len;
while ((len=inputStream.read(buff))!=-1){
fileOutputStream.write(buff,0,len);
fileOutputStream.flush();
}
inputStream.close();
fileOutputStream.close();
}
}