转换流
package com.bilibili;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
try(OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream("hello.txt"))) {
stream.write("Hello,world");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
打印流
package com.bilibili;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
try(PrintStream stream = new PrintStream(new FileOutputStream(new File("hello.txt")))) {
stream.println("zxccvbnm");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
数据流
package com.bilibili;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
try(DataOutputStream dos = new DataOutputStream(new FileOutputStream("hello.txt"))) {
dos.writeInt(23541);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象流
package com.bilibili;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("hello.txt"));
ObjectInputStream in = new ObjectInputStream(new FileInputStream("hello.txt"))) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
out.writeObject(list);
Object o = in.readObject();
System.out.println(o);
Student stu1 = new Student();
stu1.name = "jack";
stu1.age = 18;
out.writeObject(stu1);
System.out.println(in.readObject());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
static class Student implements Serializable{
private static final long serialVersionUID = 00002563;
String name;
transient int age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}