io流笔记
程序员文章站
2024-03-06 10:49:19
...
输入输出字节流
父类 OutputStream(写出) IntputStream(读入)
子类 FileOutputStream FileIntputStream
简单测试
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileOutputStream data=null;
data=new FileOutputStream("e:/data.txt",true);
String s="dwadawdDwadwa带娃";
byte []a=s.getBytes();
data.write(a);
data.flush();
data.close();
FileInputStream data1=null;
data1=new FileInputStream("e:/data.txt");
byte []b=new byte[data1.available()];
data1.read(b);
String d=new String(b);
System.out.println(d);
data1.close();
}
}
输入输出字符流
父类 Reader Writer
子类 FileReader FileWriter
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main1 {
public static void main(String[] args) throws IOException {
FileReader data=null;
data=new FileReader("e:/data.txt");
char []c=new char[100];
data.read(c);
String s=new String(c);
System.out.println(s);
data.close();
FileWriter data1=null;
data1=new FileWriter("e:/data.txt",true);
String s1="dwaFaf凡人";
data1.write(s1);
data1.close();
}
}
输入输出流(对象)
import java.io.*;
public class Main2 {
public static void main(String[] args) {
ObjectInputStream ois=null;
ObjectOutputStream oos=null;
try {
oos=new ObjectOutputStream(new FileOutputStream("d:/data.bin"));
ois=new ObjectInputStream(new FileInputStream("d:/data.bin"));
Teacher teacher=new Teacher(3000,20);
oos.writeObject(teacher);
oos.flush();
Teacher a=(Teacher)ois.readObject();
System.out.println(a);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
ois.close();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Teacher类
import java.io.Serializable;
public class Teacher implements Serializable {
private double salary;
private int age;
public Teacher(double salary, int age) {
this.salary = salary;
this.age = age;
}
@Override
public String toString() {
return "Teacher{" +
"salary=" + salary +
", age=" + age +
'}';
}
}
InputStreamReader OutoutSteamWriter(字节转字符流)PrintWriter BufferedReader
import java.io.*;
public class Buffer {
public static void main(String[] args) throws IOException {
PrintWriter br1=new PrintWriter(new OutputStreamWriter(new FileOutputStream("d:/data.txt"),"utf-8"));
br1.println("123456");
br1.println("5465656");
br1.println("6266146");
br1.println("啊啊啊啊啊");
br1.flush();
br1.close();
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("d:/data.txt"),"utf-8"));
String s=null;
while((s=br.readLine())!=null){
System.out.println(s);
}
br.close();
}
}