处理流:BufferedInputStream/Reader BufferesOutputStream/Writer
注意:当使用处理流输出时,需要使用flush来刷新流
1.使用节点流从磁盘将数据读取到内存的缓存区
2.将内存缓冲区的数据读取到处理流对应的缓冲区
3.处理流从处理流的缓冲区将数据读取
输入输出重定向 System.out -> 终端(重定向到自己的文件里面)
如果需要将自己定义的类的某个对象使用文件保存,那么这个类必须是实现了Seria;izable接口
MyClass.java
public class MyClass {
public static void main(String[] agrs) {
}
}
//字符操作
public static void buffered_io(String src, String des){
try {
//创建输入流
FileInputStream fis = new FileInputStream(src);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
//创建输出流
FileOutputStream fos = new FileOutputStream(des);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
int ch = 0;
//初级写法
// while (true) {
// ch = br.read();
// if (ch == -1){
// break;
// }
// bw.writer(ch);
// }
//进阶写法
while((ch = br. read()) != -1){
bw.writer(ch);
}
bf.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
//字节操作
public static void buffered_io_by(String src2, String des2){
try {
//字节缓冲输入流
FileInputStream fis2 = new FileInputStream(src2);
BufferedInputStream bis2 = new FileInputStream(fis2);
//字节缓冲输出流
FileOutputStream fos = new FileOutputStream(des2);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = bis2.read(buffer)) != -1){
bos.write(buffer);
}
bf.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
//输入重定向
public static void redirect_in(String src3){
try {
FileInputStream fis3 = new FileInputStream(src3);
Scanner scanner = new Scanner(fis3);
System.out.println(scanner.next());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//输入输出重定向
public static void redirect_out(String des3){
try {
PrintStream ps = new PrintStream(new FileOutputStream(des3));
System.setOut(ps);
} catch (Exception e) {
e.printStackTrace();
}
}
//保存对象
public static void saveObject(String des4){
try {
FileOutputStream fos = new FileOutputStream(des4);
ObjectOutputStream oos = new ObjectOutputStream(fos4);
Person p = new Person(name: "jack", age: 23);
oos.writeObject(p);
} catch (Exception e) {
e.printStackTrace();
}
}
//读取对象
public static void readObject(String src4){
try {
FileInputStream fis = new FileInputStream(src4);
ObjectInputStream ois = new ObjectInputStream(fis4);
Person p = (Person) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
}
Person.java
public class Person implements Serializable {
String name;
int age;
pubilc Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString90 {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}