软件设计之Java入门视频(20)
视频教程来自B站尚硅谷:
尚硅谷Java入门视频教程,宋红康java基础视频
相关文件资料(百度网盘)
提取密码:8op3
idea 下载可以关注 软件管家 公众号
学习内容:
该视频共分为1-717部分
本次内容涉及 600-629
在写代码时,总是需要来回切换界面来看代码要求,这里推荐Snipaste,可以把截图以窗口形式放在屏幕上
记录内容:
- 转换流
- 其他流的使用
- 对象流
- 随机存储文件流
1、转换流
转换流:属于字符流
1、InputStreamReader:将一个字节的输入流转换为字符的输入流
2、OutputStreamWriter:将一个字符的输出流转换为字节的输出流
作用:提供字节流与字符流之间的转换
3、解码:字节、字节数组–>字符数组、字符串
4、编码:字符数组、字符串–>字节、字节数组
@Test
public void test() {
InputStreamReader isr = null;
try {
FileInputStream fis = new FileInputStream("hello.txt");
//参数2指明了字符集,具体使用了哪个字符集,取决于文件hello.txt保存时使用的字符集
isr = new InputStreamReader(fis,"UTF-8");
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1){
String str = new String(cbuf,0,len);
System.out.print(str);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
isr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
文件复制–转换流
@Test
public void test1() throws IOException {
File file1 = new File("hello.txt");
File file2 = new File("hello_gbk.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(fos,"GBK");
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1){
osw.write(cbuf,0,len);
}
isr.close();
osw.close();
}
2、其他流的使用
1、标准的输入、输出流
2、打印流
3、数据流:用于读取或写出基本数据类型的变量或字符串
4、网络编程概述
输入流测试
键盘输入字符串,要求读取的整行字符串转成大写输出,然后继续进行输入操作。直至输入"e"或"exit"时,退出程序
public static void main(String[] args) {
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
while(true){
System.out.println("输入:");
String data = br.readLine();
if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){
System.out.println("程序结束");
break;
}
String upperCase = data.toUpperCase();
System.out.println(upperCase);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
打印流测试
@Test
public void test1() {
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
ps = new PrintStream(fos, true);
if (ps != null) {// 把标准输出流(控制台输出)改成文件
System.setOut(ps);
}
for (int i = 0; i <= 255; i++) { // 输出ASCII字符
System.out.print((char) i);
if (i % 50 == 0) { // 每50个数据一行
System.out.println(); // 换行
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
}
}
}
数据流测试
@Test
public void test1() throws IOException {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeUTF("AAA");
dos.flush();
dos.writeInt(123);
dos.flush();
dos.writeBoolean(true);
dos.flush();
dos.close();
}
@Test
public void test2() throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
String name = dis.readUTF();
int i = dis.readInt();
boolean b = dis.readBoolean();
System.out.println("name=" + name);
System.out.println("i=" + i);
System.out.println("b=" + b);
}
3、对象流
用于存储和读取
基本数据类型
或对象
的处理流,可以把Java中的对象写入到数据流中,也能把对象从数据源中还原
1、序列化:将内存中的java对象保存到磁盘中或通过网络传输出去
2、反序列化:将磁盘文件中的对象还原为内存中的一个java对象
3、可序列化类条件:
①需要实现接口Serializable
②当前类提供一个全局常量:serialVersionUID
③当前类内部所有属性也必须是可序列化的
补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
可序列化类展示
public class Person implements Serializable {
public final long serialVersionUID = 432142132L;
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
3、随机存储文件流
写进文件测试
@Test
public void test1() {
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile(new File("hello.txt"),"r");
raf2 = new RandomAccessFile(new File("world.txt"),"rw");
byte[] buffer = new byte[1024];
int len;
while ((len = raf1.read(buffer))!= -1){
raf2.write(buffer,0,len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (raf1 !=null){
try {
raf1.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (raf2 != null){
try {
raf2.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
数据插入效果实现
@Test
public void test1() throws IOException {
RandomAccessFile raf = new RandomAccessFile(new File("hello.txt"),"rw");
raf.seek(3);//将指针调到角标为3的位置
//保存指针3后面的所有数据到StringBuilder中
StringBuilder sb = new StringBuilder((int)new File("hello.txt").length());
byte[]buffer = new byte[20];
int len;
while ((len = raf.read(buffer))!= -1){
sb.append(new String(buffer,0,len));
}
//调回指针,写入xyz
raf.seek(3);
raf.write("xyz".getBytes());
//将StringBuider中的数据写入到文件中
raf.write(sb.toString().getBytes());
raf.close();
}
4、网络编程概述
IP与端口号
IP
:唯一的标识 Internet上的计算机(通信实体)
在Java中使用InetAddress类
代表IP
IP分类
:IPv4 和 IPv6; 万维网 和 局域网
域名
: www.hao123.com
本地回路地址
: 127.0.0.1 对应着localhost
如何实例化InetAddress
:两个方法:getByName(String host)、getLocalHost()
public static void main(String[] args) {
try {
InetAddress inet1 = InetAddress.getByName("192.168.10.15");
System.out.println(inet1);///192.168.10.15
InetAddress inet2 = InetAddress.getByName("www.hao123.com");
System.out.println(inet2);//www.hao123.com/153.37.235.50
InetAddress inet3 = InetAddress.getByName("127.0.0.1");
System.out.println(inet3);///127.0.0.1
//获取本地地址方式2
InetAddress inet4 = InetAddress.getLocalHost();
System.out.println(inet4);
//getHostName()
System.out.println(inet2.getHostName());//www.hao123.com
//getHostAddress()
System.out.println(inet2.getHostAddress());//153.37.235.50
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
端口号:正在计算机上运行的进程
要求:不同的进程有不同的端口号
范围:被规定为一个16位的整数,0~65535
端口号和IP地址的组合得出一个网络套接字:Socket
网络通信
TCP
@Test
public void client() {
Socket socket = null;
OutputStream os = null;
try {
//创建Socket对象,指明IP与端口号
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet,8899);
//获取一个输出流,用于输出数据
os = socket.getOutputStream();
//写出数据的操作
os.write("我是客户端".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (os != null){
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (socket !=null){
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
@Test
public void server(){
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//创建服务器端的ServerSocket,指明自己的端口号
ss = new ServerSocket(8899);
//调用accept()表示接收来自客户端的socket
socket = ss.accept();
//获取输入流
is = socket.getInputStream();
//读数据
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[5];
int len;
while ((len = is.read(buffer)) != -1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (baos !=null){
try {
baos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (is !=null){
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (ss !=null){
try {
ss.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
UDP
@Test
public void sender() throws IOException {
DatagramSocket socket = new DatagramSocket();
String str = "我是UDP方式发送的数据";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
socket.send(packet);
socket.close();
}
@Test
public void receiver() throws IOException {
DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));