1、FileWriter写数据
public static void main(String[] args) throws IOException {FileWriter fw = new FileWriter("os\\a.txt");fw.write("大得");//数组写法char[] chs = {'a', 'b', 'c', 'd', 'e'};fw.write(chs);fw.close();}
2、FileReader 读数据
public static void main(String[] args) throws IOException {FileReader fr = new FileReader("os\\a.txt");char[] ch= new char[1024];int len;while ((len = fr.read(ch)) != -1){System.out.print(new String(ch,0,len));}fr.close();}
3、BufferedWriter 字符缓冲流写数据
public static void main(String[] args) throws IOException {BufferedWriter bw = new BufferedWriter(new FileWriter("os\\a.txt"));bw.write("大得\r\n");bw.write("大得\r\n");//newLine刷新写入,close关闭也会刷新一次写入bw.newLine();bw.close();}
4、BufferedReader 字符缓冲流读数据
public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new FileReader("os\\a.txt"));char[] chs = new char[1024];int len;while ((len=br.read(chs))!=-1) {System.out.print(new String(chs,0,len));}br.close();}//创建字符缓冲输入流,readLine一直读,直到结束BufferedReader br = new BufferedReader(new FileReader("os\\a.txt"));String line;while ((line=br.readLine())!=null) {System.out.println(line);}br.close();
5、转换流(字符流中和编码解码问题相关,不同机器编码不同乱码问题)
5.1、OutputStreamWriter写数据
public static void main(String[] args) throws IOException {OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("os\\a.txt"),"utf-8");osw.write("中国");osw.close();}
5.2、InputStreamReader读数据
public static void main(String[] args) throws IOException {InputStreamReader isr = new InputStreamReader(new FileInputStream("os\\a.txt"),"utf-8");//一次读取一个字符数据int ch;while ((ch=isr.read())!=-1) {System.out.print((char)ch);}isr.close();}
6、对象序列化(写入文件看不懂的,需要反序列化)
需要implements Serializable
public class Student implements Serializable {private static final long serialVersionUID = 42L;private String name;
// private int age;private transient int age;public Student() {}public Student(String name, int age) {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 "Student{" +
// "name='" + name + '\'' +
// ", age=" + age +
// '}';
// }
}
public class ObjectStreamDemo {public static void main(String[] args) throws IOException, ClassNotFoundException {
// write();read();}//反序列化private static void read() throws IOException, ClassNotFoundException {ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myOtherStream\\oos.txt"));Object obj = ois.readObject();Student s = (Student) obj;System.out.println(s.getName() + "," + s.getAge());ois.close();}//序列化private static void write() throws IOException {ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myOtherStream\\oos.txt"));Student s = new Student("佟丽娅", 30);oos.writeObject(s);oos.close();}
}