流
流:数据交互的通道,因为在我们的计算机中,所有的内容都是通过流来传递的RTMP
流分为输出流、输入流、字节流、字符流
输入字节流InputStream
输入字符流Reader
输出字节流OutStream
输出字符流Write
例子:
InputStream is=null;
OutputStream os=null;
try {
is=new FileInputStream("d:/ll.png");
os=new FileOutputStream("d:/oo.png");
byte[] b=new byte[8];
int flag=0;
while ((flag=is.read(b))!=-1){
os.write(b);
}
os.flush(); //清理
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
序列化
序列化:将内存当中的内容,转移到硬盘或网络中
例子:字节流
public class Animal implements Serializable {
private static final long serialsionUID =-1L;
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
写入到硬盘
public class Main {
public static void main(String[] args){
Animal animal=new Animal();
animal.setName("hahaha");
FileOutputStream fos=null;
try {
fos=new FileOutputStream("D:/obj");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(animal);
oos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
读出到内存
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("D:/obj");
ObjectInputStream ois=new ObjectInputStream(fis);
Animal animal= (Animal) ois.readObject();
System.out.println(animal.getName());
}
}
Reader — Write 能传:(字符流) 文本文档 .txt .html .bat .java
不能传:(字节流).jpg .png .mkv .mps .docPrintWriter
public class Main {
public static void main(String[] args) throws IOException { FileReader fileReader=new FileReader("D:/foo.txt"); BufferedReader br=new BufferedReader(fileReader);
String str=null;
while ((str=br.readLine())!=null ) {
System.out.println(str);
}
}
}
字节流可以切换为字符流
public class Main {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream("D:/foo.txt");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader br=new BufferedReader(isr);
System.out.println(br.readLine());
}
}
字符流 写入到硬盘
FileWriter fileWriter=new FileWriter("D:/foo.txt");
// fileWriter.write("123456\r\n");
// fileWriter.write("3210");
// fileWriter.flush(); //字符流将督导的内容放入缓存区,用.flush冲刷出来
PrintWriter pw=new PrintWriter(fileWriter);
pw.println("123");
pw.println("222");
pw.flush();