day15
字符流
字符输出流
Writer是所有字符输出流的父类
OutputStreamWriter:字符输出流;
public class Test01 {
public static void main(String[] args) throws IOException {
//创建流对象
OutputStream os = new FileOutputStream("a.txt");
Writer out = new OutputStreamWriter(os);
//声明数据
char ch = '帅';
//输出数据
out.write(ch);
//刷新
out.flush();
//关闭
out.close();
}
}
tips
close()强制刷新缓冲区;如果不关,数据还在缓冲区中
flush();刷新
bufferedwriter 效率更高
字符输入流
Reader 是所有字符输入流的分类
InputStreamReader 字符输入流
public class Test01 {
public static void main(String[] args) throws IOException {
//创建对象
Reader reader = new InputStreamReader(new FileInputStream("a.txt"));
//读取
int num = reader.read();
//分析结果
System.out.println(num);
//关闭
reader.close();
}
}
BufferedReader 读取效率更高
序列化和反序列化
ObjectOutputStream
对象输出流写出的对象要保证可以序列化
就是去实现Serializable空接口
transient 的作用就是序列化的时候,不会将当前属性对应的值序列化出去
private transient int age;
-
序列化的时候记得增加序列化版本号
private static final long serialVersionUID = 1L;
public class Test01 { public static void main(String[] args) throws FileNotFoundException, IOException { //创建对象 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt")); //写出数据 //oos.write(123); //oos.writeByte(12); oos.writeInt(123); oos.writeDouble(12.12); oos.writeUTF("hello 少年"); //关闭 oos.close(); } }
tips:
当程序在序列化的时候,会默认调用类中的readReslove()方法
不重写该方法,会导致每次返回的是当前类的一个对象的副本,
该副本是一个新的对象
ObjectInputStream
public class Test01 {
public static void main(String[] args) throws FileNotFoundException, IOException {
//创建对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
//读取数据
int num = ois.readInt();
//输出数据
System.out.println(num);
//读取数据
double d = ois.readDouble();
//输出数据
System.out.println(d);
//读取数据
String s = ois.readUTF();
//输出数据
System.out.println(s);
//关闭
ois.close();
}
}
Scanner
System 对于InputStream的支持:
- System.in: 标准输入流
- System.out: 标准输出流
- System.err: 标准错误流
public class Test01 {
public static void main(String[] args) throws FileNotFoundException {
//修改标准输入流的数据源
System.setIn(new FileInputStream("a.txt"));
//Scanner对于IO的支持
Scanner input = new Scanner(System.in);
//通过Scanner获取输入数据
System.out.println(input.next());
//设置标准输出设置到文件中
System.setOut(new PrintStream(new File("c.txt")));
//通过打印 输出内容
System.out.println("hiehie");
try {
input.close();
input.next();
}catch(IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}
public class Test01 {
public static void main(String[] args) throws FileNotFoundException {
//修改标准输入流的数据源
System.setIn(new FileInputStream("a.txt"));
//Scanner对于IO的支持
Scanner input = new Scanner(System.in);
//通过Scanner获取输入数据
System.out.println(input.next());
//设置标准输出设置到文件中
System.setOut(new PrintStream(new File("c.txt")));
//通过打印 输出内容
System.out.println("hiehie");
try {
input.close();
input.next();
}catch(IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}
网络编程
网络编程:
网络:通过多台计算机构建的一个大网
-
1:为什么需要网络?
多台计算机通过网络连接,进行通信,数据交互、数据共享。
去除地域限制 拉近人与人之间的举例
-
2:网络通信的基石:
三大基石(ip标示计算机 协议通信规则 端口定位应用程序)
-
端口: 2个字节 65536个 0-65536之间
虚拟的概念
0-1024之间的端口是系统保留端口
22 21
3306 8521 8080 80