Day24

2023-12-29 11:57:01

Day24

一,对象流

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Test03 {
	/**
	 * 知识点:利用对象输出流 向文件写入自定义对象
	 */
	public static void main(String[] args) throws IOException {
		//1.创建流对象
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("io.txt"));
		
		//写入数据
		oos.writeObject(new User("1810466136", "123123", "金刚芭比", "寒冰射手", 10000, 8000));
		oos.writeObject(new User("1444911642", "123456", "死亡如风", "亚索", 1000, 50));
		oos.writeObject(new User("1048312408", "111222", "撕裂的忧伤", "塞拉斯", 8000, 6000));
		oos.writeObject(new User("2929954193", "123321", "leoy", "盲僧", 5000, 2000));
		oos.writeObject(null);
		
		//3.关闭资源
		oos.close();
		
		
	}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Test04 {
	/**
	 * 知识点:利用对象输入流 读取文件里的自定义对象
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		//1.创建流对象
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("io.txt"));
		
		//读取数据
		User user;
		while((user = (User) ois.readObject()) != null){
			System.out.println(user);
		}
		
		//3.关闭资源
		ois.close();	
	}
}

import java.io.Serializable;

public class User implements Serializable{
	
	private static final long serialVersionUID = -7113110317387504182L;
	
	private String username;
	private transient String password;
	private String nickName;
	private String role;
	private double hp;
	private double mp;
	
	public User() {
	}

	public User(String username, String password, String nickName, String role, double hp, double mp) {
		this.username = username;
		this.password = password;
		this.nickName = nickName;
		this.role = role;
		this.hp = hp;
		this.mp = mp;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNickName() {
		return nickName;
	}

	public void setNickName(String nickName) {
		this.nickName = nickName;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public double getHp() {
		return hp;
	}

	public void setHp(double hp) {
		this.hp = hp;
	}

	public double getMp() {
		return mp;
	}

	public void setMp(double mp) {
		this.mp = mp;
	}

	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", nickName=" + nickName + ", role=" + role
				+ ", hp=" + hp + ", mp=" + mp + "]";
	}
}

二,内存流

1.内存输出流

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Test01 {
	/**
	 * 知识点:内存输出流
	 */
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象 - 默认缓冲区:32个字节
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		//2.写入数据(将数据写入到ByteArrayOutputStream对象里的缓冲数组中 - byte[] buf)
		baos.write("用良心做教育".getBytes());
		
		//获取缓冲区里的数据
		byte[] byteArray = baos.toByteArray();
		System.out.println(new String(byteArray));
		
		String str = baos.toString();
		System.out.println(str);
	}
}

2,内存输入流

import java.io.ByteArrayInputStream;
import java.io.IOException;

public class Test02 {
	/**
	 * 知识点:内存输入流
	 */
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象(将byte数组赋值给底层的buf)
		ByteArrayInputStream bais = new ByteArrayInputStream("用良心做教育".getBytes());
		
		//2.读取数据
		byte[] bs = new byte[1024];
		int len;
		while((len = (bais.read(bs))) != -1){
			System.out.println(new String(bs, 0, len));
		}
		
	}
}

三,打印流

1,字节打印流

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class Test01 {
	/**
	 * 知识点:字节打印流
	 */
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象
		//PrintStream ps = new PrintStream("io.txt");
		//PrintStream ps = new PrintStream(new File("io.txt"));
		PrintStream ps = new PrintStream(new FileOutputStream("io.txt",true));
		
		//2.写入数据
		ps.println("用良心做教育");
		
		//3.关闭资源
		ps.close();
	}
}

2,字符打印流

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Test02 {
	/**
	 * 知识点:字符打印流
	 */
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象
		//PrintWriter pw = new PrintWriter("io.txt");
		//PrintWriter pw = new PrintWriter(new File("io.txt"));
		//PrintWriter pw = new PrintWriter(new FileOutputStream("io.txt",true));
		PrintWriter pw = new PrintWriter(new FileWriter("io.txt",true));
		
		//2.写入数据
		pw.println("用良心做教育");
		
		//3.关闭资源
		pw.close();
	}
}

3,重定向

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;

public class Test03 {
	/**
	 * 知识点:重定向
	 * 
	 * 系统标准的输入流:方向(控制台->程序)
	 * InputStream in = System.in;
	 */
	public static void main(String[] args) throws FileNotFoundException {
		
		//重定向 - 重新定义系统标准输入流的方向:文件->程序
		System.setIn(new FileInputStream("io.txt"));
		
		InputStream in = System.in;
		Scanner scan = new Scanner(in);
		
		String str = scan.next();
		System.out.println(str);
		
		scan.close();
	}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class Test04 {
	/**
	 * 知识点:重定向
	 * 
	 */
	public static void main(String[] args) throws FileNotFoundException {
		
		//重新定义系统标准输出流的方向:程序->文件
		System.setOut(new PrintStream(new FileOutputStream("io.txt",true)));
		
		//系统标准的输出流:方向(程序->控制台)
		PrintStream out = System.out;
		out.println("彩虹小可爱,皇冠给你带");
	}
}

四,随机访问流

1,写入数据

import java.io.IOException;
import java.io.RandomAccessFile;

public class Test01 {
	/**
	 * 知识点:利用随机访问流写入数据
	 */
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象
		RandomAccessFile w = new RandomAccessFile("io.txt", "rw");
		
		//2.写入数据
		w.write("123abc木头人".getBytes());
		
		//3.关闭资源
		w.close();
		
	}
}



import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class Test02 {
	/**
	 * 知识点:利用随机访问流写入数据 -- 末尾追加
	 */
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象
		File file = new File("io.txt");
		RandomAccessFile w = new RandomAccessFile(file, "rw");
		
		//设置指针
		w.seek(file.length());
		
		//2.写入数据
		w.write("123abc木头人".getBytes());
		
		//3.关闭资源
		w.close();
		
	}
}

2,读取数据

import java.io.IOException;
import java.io.RandomAccessFile;

public class Test03 {
	/**
	 * 知识点:利用随机访问流 读取文件里的数据
	 */
	public static void main(String[] args) throws IOException {
		
		//1.创建流对象
		RandomAccessFile r = new RandomAccessFile("io.txt", "r");
		
		//2.读取数据
		byte[] bs = new byte[1024];
		int len;
		while((len = r.read(bs)) != -1){
			System.out.println(new String(bs,0,len));
		}
		
		//3.关闭资源
		r.close();
	}
}

3,拷贝数据

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class Copy {
	/**
	 * 知识点:拷贝文件 -- 断点续传
	 */
	public static void main(String[] args) throws IOException {
		
		RandomAccessFile r = new RandomAccessFile("水野朝阳.mp4", "r");
		File targetFile = new File("copy.mp4");
		RandomAccessFile w = new RandomAccessFile(targetFile, "rw");
		
		long length = targetFile.length();
		r.seek(length);
		w.seek(length);
		
		byte[] bs = new byte[1024];
		int len;
		while((len = r.read(bs)) != -1){
			w.write(bs, 0, len);
		}
		
		r.close();
		w.close();
	}
}

五,网络编程–TCP协议

1,一对一(发一句收一句)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

//客户端
public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		//注意:关闭流,等同于关闭Socket
		
		//王晨曦
		Socket socket = new Socket("127.0.0.1", 8080);
		
		//1.向服务端发送数据
		PrintStream ps = new PrintStream(socket.getOutputStream());
		ps.println("王晨曦:妹妹,你多大了?");
		
		//4.接受来自服务端的消息
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
		String readLine = br.readLine();
		System.out.println(readLine);
		
		ps.close();
		br.close();
		socket.close();
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class Server {

	public static void main(String[] args) throws IOException {
		
		//注意:关闭流,等同于关闭Socket
		
		//大堂经理
		ServerSocket server = new ServerSocket(8080);
		
		//18号技师
		Socket socket = server.accept();
		
		//2.接受来自客户端的消息
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
		String readLine = br.readLine();
		System.out.println(readLine);
		
		
		//3.向客户端发送数据
		PrintStream ps = new PrintStream(socket.getOutputStream());
		ps.println("18号技师:刚满18岁");
		
		br.close();
		ps.close();
		socket.close();
		server.close();
		
	}
}

2,一对一(一直发一直收)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//服务端
public class Server {

	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(8080);
		
		Scanner scan = new Scanner(System.in);
		
		Socket socket = server.accept();
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
		PrintStream ps = new PrintStream(socket.getOutputStream());
		while(true){
			
			String readLine = br.readLine();
			System.out.println(readLine);
			
			ps.println("18号技师:" + scan.next());
		}
	}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
	/**
	 * 知识点:一对一聊天
	 */

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1", 8080);
		
		Scanner scan = new Scanner(System.in);
		
		PrintStream ps = new PrintStream(socket.getOutputStream());
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
		while(true){
			
			ps.println("王晨曦:" + scan.next());
			
			String readLine = br.readLine();
			System.out.println(readLine);
		}
		
	}
}

3,一对一(发,收多句)–利用线程

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(8080);
		
		Socket socket = server.accept();
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		while(true){
			ps.println("18号技师:" + scan.next());
		}
	}
}
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
	/**
	 * 知识点:优化一对一聊天
	 */

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1", 8080);
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		while(true){
			ps.println("王晨曦:" + scan.next());
		}
		
	}
}
//线程
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ReceiveThread extends Thread{
	
	private Socket socket;
	
	public ReceiveThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		
		while(true){
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
				String readLine = br.readLine();
				System.out.println(readLine);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
}

4,群聊


import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

public class Server {
	
	//socket容器
	public static final ConcurrentHashMap<String, PrintStream> map = new ConcurrentHashMap<>();

	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(8080);
		
		while(true){
			
			Socket socket = server.accept();
			
			//获取客户端的IP地址
			String ip = socket.getInetAddress().getHostName();
			System.out.println(ip);
			
			PrintStream ps = new PrintStream(socket.getOutputStream());
			
			map.put(ip, ps);
			
			new ServerThread(socket).start();
		}
		
		
	}
}

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
	/**
	 * 知识点:群聊
	 */

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1", 8080);
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		while(true){
			ps.println("王晨曦:" + scan.next());
		}
		
	}
}
//线程
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ServerThread extends Thread{
	
	private Socket socket;
	
	public ServerThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		//接受当前客户端的消息,并返回给其他客户端
		
		ConcurrentHashMap<String,PrintStream> map = Server.map;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
			while(true){
				String readLine = br.readLine();
				System.out.println(readLine);
				
				Set<Entry<String,PrintStream>> entrySet = map.entrySet();
				for (Entry<String, PrintStream> entry : entrySet) {
					String ip = entry.getKey();
					if(!socket.getInetAddress().getHostName().equals(ip)){
						PrintStream ps = entry.getValue();
						ps.println(readLine);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
//线程
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ReceiveThread extends Thread{
	
	private Socket socket;
	
	public ReceiveThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		
		while(true){
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
				String readLine = br.readLine();
				System.out.println(readLine);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
}

六,网络编程–UDP协议

1,一对一

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Client01 {
	
	public static void main(String[] args) throws Exception {
		
		DatagramSocket socket = new DatagramSocket(7070);
		
		//1.向Client02发送数据
		byte[] buf = "电动跳跳恐龙蛋".getBytes();
		DatagramPacket p = new DatagramPacket(buf , 0, buf.length, InetAddress.getByName("127.0.0.1"), 8080);
		socket.send(p);
		
		//4.接收来自Client02的数据
		buf = new byte[1024];
		p = new DatagramPacket(buf, 0, buf.length);
		socket.receive(p);
		System.out.println(new String(buf).trim());
		
	}
}

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Client02 {
	
	public static void main(String[] args) throws Exception {
		
		DatagramSocket socket = new DatagramSocket(8080);
		
		//2.接收来自Client01的数据
		byte[] buf = new byte[1024];
		DatagramPacket p = new DatagramPacket(buf, 0, buf.length);
		socket.receive(p);
		System.out.println(new String(buf).trim());
		
		//3.向Client01发送数据
		buf = "一比一高达模型".getBytes();
		p = new DatagramPacket(buf , 0, buf.length, InetAddress.getByName("127.0.0.1"), 7070);
		socket.send(p);
	}
}

2,一对一(连说)

import java.net.DatagramSocket;

public class Client01 {
	
	public static void main(String[] args) throws Exception {
		
		DatagramSocket socket = new DatagramSocket(7070);
		
		new ReceiveThread(socket).start();
		new SendThread("127.0.0.1", 8080, "王波", socket).start();
		
	}
}
import java.net.DatagramSocket;

public class Client02 {
	
	public static void main(String[] args) throws Exception {
		
		DatagramSocket socket = new DatagramSocket(8080);
		
		new ReceiveThread(socket).start();
		new SendThread("127.0.0.1", 7070, "袁黄彬", socket).start();
	}
}

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ReceiveThread extends Thread{
	
	private DatagramSocket socket;
	
	public ReceiveThread(DatagramSocket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		while(true){
			byte[] buf = new byte[1024];
			DatagramPacket p = new DatagramPacket(buf, 0, buf.length);
			try {
				socket.receive(p);
				System.out.println(new String(buf).trim());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class SendThread extends Thread{

	private String ip;
	private int port;
	private String nickName;
	private DatagramSocket socket;
	
	public SendThread(String ip, int port, String nickName, DatagramSocket socket) {
		this.ip = ip;
		this.port = port;
		this.nickName = nickName;
		this.socket = socket;
	}

	@Override
	public void run() {
		Scanner scan = new Scanner(System.in);
		while(true){
			byte[] buf = (nickName + ":" + scan.next()).getBytes();
			try {
				DatagramPacket p = new DatagramPacket(buf , 0, buf.length, InetAddress.getByName(ip), port);
				socket.send(p);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

七,网络编程–http

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test01 {
	public static void main(String[] args) throws Exception {
		
		//链接对象
		URL url = new URL("https://suggest.taobao.com/sug?code=gbk&q=始祖鸟&callback=cb");
	
		//获取连接对象
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		
		//设置参数
		connection.setDoInput(true);//允许使用输入流
		connection.setDoOutput(true);//允许使用输出流
		connection.setConnectTimeout(5000);//设置连接超时时间
		connection.setReadTimeout(5000);//设置读取超时时间
		
		//获取响应状态码
		int code = connection.getResponseCode();
		
		if(code == HttpURLConnection.HTTP_OK){
			
			//获取数据
			InputStream in = connection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			
			char[] cs = new char[1024];
			int len;
			while((len = br.read(cs)) != -1){
				System.out.println(new String(cs,0,len));
			}
			
			in.close();
			
		}else if(code == HttpURLConnection.HTTP_NOT_FOUND){
			System.out.println("抱歉,网页未找到");
		}
	}
}
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test02 {
	public static void main(String[] args) throws Exception {
		
		//链接对象
		URL url = new URL("https://p9.itc.cn/q_70/images03/20201010/879e2dfb54ac4118b22a412bdcc79cca.jpeg");
	
		//获取连接对象
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		
		//设置参数
		connection.setDoInput(true);//允许使用输入流
		connection.setDoOutput(true);//允许使用输出流
		connection.setConnectTimeout(5000);//设置连接超时时间
		connection.setReadTimeout(5000);//设置读取超时时间
		
		//获取响应状态码
		int code = connection.getResponseCode();
		
		if(code == HttpURLConnection.HTTP_OK){
			
			//获取数据
			InputStream in = connection.getInputStream();
			FileOutputStream out = new FileOutputStream("相泽南.jpg");
			
			byte[] bs = new byte[1024];
			int len;
			while((len = in.read(bs)) != -1){
				out.write(bs, 0, len);
			}
			
			in.close();
			out.close();
			
		}else if(code == HttpURLConnection.HTTP_NOT_FOUND){
			System.out.println("抱歉,网页未找到");
		}
	}
}

文章来源:https://blog.csdn.net/haikeydnk/article/details/135284797
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。