您的位置:首页 > 编程语言 > Java开发

Java初学几天的总结——一个菜鸡的自我学习之路(10)

2020-03-23 18:28 316 查看

流的应用

import java.io.IOException;

public class Main {
public static void main(String[] args) {
try {
Socket socket = new Socket(InetAddress.getByName("localhost"), 12345);
PrintWriter out = new PrintWriter(    //往服务器中写入数据
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())));
out.println("Hello");
out.flush();//刷新
BufferedRead in = new BufferedReader(    //读出服务器中的数据
new InputStreamReader(
socket.getInputStream()));
String line;
line = in.readLine();
System.out.println(line);
out.close();
socket.close();
} catch (IOException e) {
e,printStackTrace();
}
}
}

阻塞/非阻塞

read()函数是阻塞的,在读到所需的内容之前会停下来等
使用read()的更“高级”的函数,如nextInt()、readLine()都是这样的
所以常用单独的线程来做socket读的等待,或使用nio的channel选择机制
对于socket,可以设置SO时间
setSoTimeout(int timeOut)

对象串行化

ObjectInputStream类
readObject()
ObjectOutputStream类
writeObject()
Serializable接口
import java.io.IOException;

class Student implements Serializable {    //加入一个接口:可以被串行化的类
private String name;
private int age;
private int grade;

public Student(String name, int age, int grade) {
this.name = name;
this.age = age;
this.grade = grade;
}

public String toString() {
return name+" "+age+" "+grade;
}
}

public class Main {
public static void main(String[] args) {
try {
Student s1 = new Student("John", 18, 5);
System.out.println(s1);
//构建一个可以将s1直接写道文件里的方式是
ObjectOutputStream out = new ObjectOutputStream(    //这个流的实现需要建立在一个实体的流的基础上
new FileOutputStream("obj.dat"));
out.writeObject(s1);
out.close();
//将数据读出来
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("obj.dat");
Student s2 = ()Student)in.readObject();
System.out.out.println(s2);
in.close();
//判断s1和s2是否是相同的
System.out.println(s1==s2);
//当我们往流中读入一个新的数据时,会建一个对象来读入,当我们从流中构造一个对象来读取数据时,这个对象回事一个全新的对象
} catch (IOException e) {
e,printStackTrace();
} catch (ClassNotFoundException e) {
e,printStackTrace();
}
}
}

以上就是我Java入门所作的所有笔记了,欢迎大家提出建议。

  • 点赞
  • 收藏
  • 分享
  • 文章举报
芝识就是力量 发布了117 篇原创文章 · 获赞 16 · 访问量 2万+ 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: