这是我参与更文挑战的第5天,活动详情查看: 更文挑战
1.Ip对应类的对象
Ip对应类的对象:InetAddress
两个实例化的方法:InetAddress.getByName(String host)/InetAddress.getLocalHost()
两个常用的方法:getHostName(),getHostAdress()。
2.传输层的TCP协议和UDP协议的主要区别
TCP:可靠的数据传输(三次握手);进行大数据量的传输;效率低
UDP:不可靠;以数据报形式发送,数据包限定为64k;效率更高。
URL
URL:统一资源定位符
URL url=new URL (“http://localhost:8080/examples/1.jpg“);
3.对象序列化机制的理解
序列化:允许把内存中的java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点
反序列化:当其他程序获取了这种二进制流,就可以恢复成原来的Java对象
4.实现序列化条件
- 实现接口:Serializable 标识接口
- 对象所在的类提供常量:序列版本号
- 要求对象的属性也是可序列化的。(基本数据类型本身是可序列化的)
java对象Person
package ObjectInoutOutputTest;
import java.io.Serializable;
public class Person implements Serializable {
/*
1.实现接口Serializable(标识接口)
2.当前类提供一个全局的常量:serialVersionUID
3.除了当前的类需要实现Serializable接口外,还必须保证内部的所有属性也必须是可序列化的。
ObjectOutputStrea和ObjectInputStream不能序列化static和transient修饰的成员变量
*/
public static final long serialVersionUID = 8365573970943482803L;
private String name;
private int age;
public Person(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;
}
public Person() {
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
复制代码
序列化
package ObjectInoutOutputTest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class xuliehua {
/*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream实现
*/
public static void main(String[] args) {
ObjectOutputStream oos=null;
try {
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new String("我爱北京天安门"));
oos.flush();
oos.writeObject(new Person("小王",23));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
复制代码
反序列化
package ObjectInoutOutputTest;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
public class fanxulie {
/*
反序列化:将磁盘文件中的对象还原为内存中的一个java对象
使用ObjectInputStream
*/
public static void main(String[] args) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
String str = (String) obj;
Person p = (Person) ois.readObject();
System.out.println(str);
System.out.println(p);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END