day01_io01
1.利用缓冲流,采用不同方式 ,实现图片视频的复制功能,并记录时间 比较效率
图片素材
package day15.homework.work1;import java.io.*;public class W03ManBuffer {/**方式一,利用字节有缓冲流*/public static void main(String[] args) throws IOException {//1.新建输入流对象FileInputStream in = new FileInputStream("C:\\Users\\11924\\Desktop\\樱木花道.jpg");BufferedInputStream bufferedInputStream = new BufferedInputStream(in);//2.输出流对象FileOutputStream out = new FileOutputStream("C:\\Users\\11924\\Desktop\\copy3.jpg");BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);int readDate;//#开始时间戳记录时间long start = System.currentTimeMillis();while ((readDate = bufferedInputStream.read()) != -1) {bufferedOutputStream.write(readDate);}//#结束时间戳long end = System.currentTimeMillis();System.out.println(end - start);//3.结束in.close();out.close();}}
package day15.homework.work1;
import java.io.*;
public class W04KuaiBuffer {
/**方式四,利用数组,有缓冲流*/
public static void main(String[] args) throws IOException {
//1.新建输入流对象
FileInputStream in = new FileInputStream("C:\\Users\\11924\\Desktop\\樱木花道.jpg");
BufferedInputStream bufferedInputStream = new BufferedInputStream(in);
int readCount;
byte[] bytes = new byte[1024];
bufferedInputStream.read(bytes);
//2.输出流对象
FileOutputStream out = new FileOutputStream("C:\\Users\\11924\\Desktop\\copy4.jpg");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
//#开始时间戳记录时间
long start = System.currentTimeMillis();
while ((readCount=bufferedInputStream.read(bytes))!=-1){
bufferedOutputStream.write(bytes,0,readCount);
}
//#结束时间戳
long end = System.currentTimeMillis();
System.out.println(end - start);
//3.结束
in.close();
out.close();
}
}
运行结果
| 时间 | 无缓冲区 | 有缓冲区 |
|---|---|---|
| 字节 | 498 | 14 |
| 数组 | 1 | 0 |
2.有这样的一个words数组,数组中每个字符串的格式为“词性:单词”
String[] words = {“verb:eat”,”verb:drink”,”verb:sleep”,”verb:play”,”noun:rice”,”noun:meat”,”noun:hand”,”noun:hair”};
根据单词性质动词verb全部存入verb.txt文件中
根据单词性质名词noun全部存入noun.txt文件中
package day15.homework;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**1.有这样的一个words数组,数组中每个字符串的格式为“词性:单词”
String[] words = {"verb:eat","verb:drink","verb:sleep","verb:play","noun:rice","noun:meat","noun:hand","noun:hair"};
根据单词性质动词verb全部存入verb.txt文件中
根据单词性质名词noun全部存入noun.txt文件中
*/
public class Work2Words {
public static void main(String[] args) {
String[] words=new String[]{"verb:eat","verb:drink","verb:sleep","verb:play","noun:rice","noun:meat","noun:hand","noun:hair"};
String verb = "verb";
String noun = "noun";
//单词分类判断包含verb或者noun分别放进两个字符串中
String verbs="";
String nouns="";
for (int i = 0; i < words.length; i++) {
if(words[i].contains(verb)){
verbs+=words[i]+"\n";
}
if(words[i].contains(nouns)){
nouns+=words[i]+"\n";
}
}
File verbFile = new File("C:\\Users\\11924\\Desktop\\verbs.txt");
File nounFile = new File("C:\\Users\\11924\\Desktop\\nouns.txt");
FileOutputStream verbFileOutputStream = null;
FileOutputStream nounFileOutputStream = null;
try{
//初始化输出流
verbFileOutputStream = new FileOutputStream(verbFile);
nounFileOutputStream = new FileOutputStream(nounFile);
//获得字节组
byte[]verbByte=verbs.getBytes();
byte[]nounByte=nouns.getBytes();
//输出
verbFileOutputStream.write(verbByte);
nounFileOutputStream.write(nounByte);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}finally{
try {
if (verbFileOutputStream != null){
verbFileOutputStream.close();
}
if (nounFileOutputStream != null){
nounFileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package day15.homework;
import java.io.*;
//2. 递归查找指定目录中(包括子目录中),所有的.java文件,
// 并且,把所有这些找到的java文件,复制(是复制不是移动)到一个指定的目录下
// 目录结构同长风老师最后一次作业
public class Work3Copy {
public static void main(String[] args) {
FileHandler fileHandler = null;
try {
File dir =new File("C:\\Users\\11924\\Desktop\\firstLevel");
fileHandler =new FileHandler("C:\\Users\\11924\\Desktop\\result");
fileHandler.findFile(dir, new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname != null
&& pathname.isFile()
&& pathname.getName().endsWith(".java");
}
});
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class FileHandler{
/**方法 fileHandler findFile copyFile closeQuietly */
File dir;
public FileHandler(String recordPath) throws FileNotFoundException {
//利用目标文件的路径字符串,初始化,表示用来存储文件名的文件的File对象
dir = new File(recordPath);
//确保目标目录存在
dir.mkdirs();
}
// 利用该方法,使用由FileFilter对象,所指明的筛选条件,筛选出符合条件的文件
// 并将这些文件的绝对路径,保存到指定文件中
public void findFile(File file, FileFilter filter) throws IOException {
File[] files = file.listFiles();
if (files == null) {
//说明当前File dir其实表示的是一个文件
if (filter.accept(file)) {
//满足筛选条件,就将满足条件的文件复制到目标目录下
//创建File对象,表示复制的目标文件
File destFile = new File(dir, file.getName());
copyFile(file, destFile);
}
return;
}
for (int i = 0; i < files.length; i++) {
findFile(files[i], filter);
}
}
/**利用缓冲流完成文件的复制*/
public void copyFile(File srcFile, File destFile) {
// 创建缓冲输入字节流对象
InputStream in = null;
// 创建缓冲字节输出流对象
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(srcFile));
out = new BufferedOutputStream(new FileOutputStream(destFile));
int len;
byte[] buffer = new byte[1024];
//复制文件
while((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭输入流
closeQuietly(in);
//关闭输出流
closeQuietly(out);
}
}
private void closeQuietly(Closeable closeable) {
//关闭输出流
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
day02_io02
1. 从磁盘上读取一个文本文件(如某个java源代码),分别统计出文件中英文字母、空格、数字字符的个数。(注意文本文件中的数字指的是数字字符!!!)
package day02ZiFuliu.Work;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
/**1. 从磁盘上读取一个文本文件(如某个java源代码),分别统计出文件中英文字母、空格、数字字符的个数。(注意文本文件中的数字指的是数字字符!!!)*/
public class Work1 {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream(
"C:\\Users\\11924\\IdeaProjects\\file\\ReaderConstractor.java");
Reader reader=new InputStreamReader(fis);
int readDate;
int numLetter=0;
int numSpace=0;
int numNum=0;
while ((readDate=reader.read())!=-1){
char c=(char)readDate;
if(c>='a'&&c<='z'||c>='A'&&c<='Z') numLetter++;
if(c>='0'&&c<='9') numNum++;
if(c==' ') numSpace++;
}
System.out.println("最后统计结果是:英文字母有"+numLetter+"个;");
System.out.println("最后统计结果是:空格有"+numSpace+"个;");
System.out.println("最后统计结果是:数字字符有"+numNum+"个;");
reader.close();
}
}

2. 在一个磁盘的文件里保存26个英文小写字母(乱序),将他们读入内存中,进行排序,把排好顺序的数再重新追加写到磁盘的该文件中。
package day02ZiFuliu.Work;
import java.io.*;
/**
* 2. 在一个磁盘的文件里保存26个英文小写字母(乱序),将他们读入内存中,进行排序,把排好顺序的数再重新追加写到磁盘的该文件中。
*/
public class Work2 {
public static void main(String[] args) throws IOException {
//创建输入流对象
//Reader reader = new BufferedReader(new FileReader("C:\\Users\\11924\\IdeaProjects\\file\\letter.txt"))
Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\11924\\IdeaProjects\\file\\letter.txt")));
//读入数据
char[] chars = new char[1024];
int readCount = reader.read(chars);
//数据chars进行排序
//sorted代表排好序的数组
sort(chars);
//创建输出流对象
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
"C:\\Users\\11924\\IdeaProjects\\file\\letter.txt", true)));
//创建FileOutputStream流以写入数据到File对象表示的文件。 如果第二个参数为true,则字节将写入文件的末尾而不是开头。就是接着写而不是重新写
writer.write("\r\n");
//写入排好序的内容
writer.write(chars);
//关闭输入输出
writer.close();
reader.close();
}
//插入排序
public static void sort(char[] arr) {
if (arr.length >= 2) {
for (int i = 1; i < arr.length; i++) {
//挖出一个要用来插入的值,同时位置上留下一个可以存新的值的坑
int x = arr[i];
int j = i - 1;
//在前面有一个或连续多个值比x大的时候,一直循环往前面找,将x插入到这串值前面
while (j >= 0 && arr[j] > x) {
//当arr[j]比x大的时候,将j向后移一位,正好填到坑中
arr[j + 1] = arr[j];
j--;
}
//将x插入到最前面
arr[j + 1] = (char) x;
}
}
}
}
day03_io03
第一题:
1.自己定义一个类,实现序列化与反序列化的过程。(定义的成员变量除了基本数据类型也可以是其他类的引用)
2.修改类,用固定的serialVersionUID去读取。
package day03.Work;
import java.io.*;
/**1.自己定义一个类,实现序列化与反序列化的过程。(定义的成员变量除了基本数据类型也可以是其他类的引用)
2.修改类,用固定的serialVersionUID去读取。
*/
public class Work01ProjectSteam {
public static void main(String[] args) {
Hero h = new Hero();
h.name="盖伦";
h.hp=616;
File file = new File("C:\\Users\\11924\\IdeaProjects\\file\\Hero.txt");
try (FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);){
oos.writeObject(h);
Hero h2=(Hero) ois.readObject();
System.out.println(h2.name);
System.out.println(h2.hp);
}catch (IOException e){
e.printStackTrace();
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
}
class Hero implements Serializable {
private static final long serialVersionUID=1L;
public String name;
public float hp;
}
第二题:自己总结IO流相关的知识点,按照上课的Excel里的样子,自己归纳一下学过的16个类,搞清楚每个类的用法,最好自己能够默写出来
| 字节输出流 | 输入流 | 字符输出流 | 输入流 | |
|---|---|---|---|---|
| 四种基类 | OutputStream | InputStream | Writer | Reader |
| 文件类file | FileOutputStream | FileInputStream | FileWriter | FileReader |
| 缓冲流Buffered | BufferedOutputStream | BufferedInputStream | BufferedWriter | BufferedReader |
| 转换流 | OutputStreamWriter | InputStreamReader | ||
| 数据流 | DateOutputStream | DateInputStream | ||
| 序列化流 | ObjectOutputStream | ObjectInputStream | ||
| 打印流(只有输出) | PrintStream | PrintWriter |
day04_thread01
1.自己利用线程的第一种实现方式,和第二种实现方式 实现如下功能(多线程引例):
a. 程序不停地在屏幕上输出一句问候的语句(比如“你好”)
(时间间隔一定要大些比如3s(或大于3s),因为在控制台窗口,输入和输出不能同时发生,
我们只能在两次输出“你好”的间隙,从键盘输入数据,才能保证键盘输入被正确接收)
b.同时,当我通过键盘输入固定响应的时候,程序停止向屏幕输出问候的语句
1.thread
package day04.work;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class W1_1Thread {
public static boolean flag=true;
public static void main(String[] args) {
Hello hello = new Hello();
hello.start();
Stop stop = new Stop();
stop.start();
}
//你好的程序
static class Hello extends Thread{
@Override
public void run() {
while (W1_1Thread.flag){
System.out.println("你好");
try {
//程序暂停一下,进行输入
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
//停止的程序
static class Stop extends Thread{
@Override
public void run() {
Scanner in = new Scanner(System.in);
while (W1_1Thread.flag){
String s=in.nextLine();
if("stop".equals(s)){
System.out.println("我要停止了");
W1_1Thread.flag=false;
break;
}
}
}
}
}

runnable
package day04.work;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class W1_2Runnable {
public static boolean flag=true;
public static void main(String[] args) {
WorkThread2 workThread2 = new WorkThread2();
Stop2 stop2 = new Stop2();
new Thread(workThread2).start();
new Thread(stop2).start();
}
static class WorkThread2 implements Runnable{
@Override
public void run() {
while (W1_2Runnable.flag){
System.out.println("你好");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
static class Stop2 implements Runnable{
@Override
public void run() {
Scanner in = new Scanner(System.in);
while (W1_2Runnable.flag){
String s=in.nextLine();
if("stop".equals(s)){
System.out.println("我要停止了");
W1_2Runnable.flag=false;
break;
}
}
}
}
}

2.重点内容
2.1理解记忆进程,线程,串行,并行,并发相关概念
| 进程 | 通俗讲:正在运行的程序或软件 |
|---|---|
| 线程 | 在进程中有多个子任务:每一个子单元就是一个进程 |
| 串行 | 一个任务一个任务顺序执行 |
| 并行 | 多个任务同一时间点执行 |
| 并发 | 多个任务在同一时间段执行 |
2.2理解记忆线程生命周期图,并自己画一画,搞清楚各个状态之间的转化

2.3关于课上API的代码敲一下,理解线程合并,守护,礼让等
1.加入join
2.守护Daemon
package day04.work;
public class W2_2Daemon{
public static void main(String[] args) {
Protect protect = new Protect();
Thread t = new Thread(protect);
t.setDaemon(true);
t.start();
new Thread(new Princess()).start();
}
}
class Protect implements Runnable{
@Override
public void run() {
while (true){
System.out.println("守护公主的将军");
}
}
}
class Princess implements Runnable{
@Override
public void run() {
for (int i = 0; i < 2; i++) {
System.out.println("公主");
}
}
}


3.礼让yield
宋红康
1.集合Collection中存储的如果是自定义类的对象,需要自定义类重写哪个方法?为什么?
2.ArrayList,LinkedList,Vector三者的相同点与不同点?【面试题】
3.List 接口的常用方法有哪些?(增、删、改、查、插、长度、遍历)。
4.如何使用lterator 和增强for 循环遍历List。举例说明。
5.Set存储数据的特点是什么?常见的实现类有什么?说明一下彼此的特点。
day05_thread02
1. 用多线程代码来模拟,迅雷用3个线程下载100M资源的的过程。
每个线程每次,一次下载1兆(M)资源,直到下载完毕,即剩余的待下载资源大小为0
(用一个整数表示资源大小,每次个线程每次下载多少兆(M), 剩余待下载资源就减少多少兆(M),
模拟我们售票的代码实现,考虑多线程的数据安全问题)
第一版错误结果:
有0与-1,没考虑到0与-1,需要上锁
//错误版本
package day05.Work;
public class DownloadMovie {
public static void main(String[] args) {
Xunlei xunlei = new Xunlei(300);
Thread thread1 = new Thread(xunlei, "线程1");
Thread thread2 = new Thread(xunlei, "线程2");
Thread thread3 = new Thread(xunlei, "线程3");
thread1.start();
thread2.start();
thread3.start();
}
}
class Xunlei implements Runnable{
int fileSize;
public Xunlei(int fileSize) {
this.fileSize = fileSize;
}
@Override
public void run() {
while (fileSize>0){
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"还剩余"+fileSize--+"M");
}
}
}
第二版加入synchronized
防止
package day05.Work;
public class DownloadMovie {
public static void main(String[] args) {
Xunlei xunlei = new Xunlei(300);
Thread thread1 = new Thread(xunlei, "线程1");
Thread thread2 = new Thread(xunlei, "线程2");
Thread thread3 = new Thread(xunlei, "线程3");
thread1.start();
thread2.start();
thread3.start();
}
}
class Xunlei implements Runnable{
int fileSize;
Object obj = new Object();
public Xunlei(int fileSize) {
this.fileSize = fileSize;
}
@Override
public void run() {
synchronized (obj){
while (fileSize>0){
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"还剩余"+fileSize--+"M");
}
}
}
}
2. 创建2个线程,打印从0到99这100个数字,要求线程交叉顺序打印。
要求使用线程间通信实现。即我打印一个数字,你打印一个数字,两线程协作完成。<br />比如:<br /> 线程1: 0<br /> 线程2: 1<br /> 线程1: 2<br /> 线程2: 3<br /> 线程1: 4<br /> 线程2: 5
day07_network
1.利用多线程的方式去改造UDP v3版本代码
packet oneperson
SendTask:专门用来做发送数据
ReceiveTask :专门用来接收数据
利用Runnable的方式去做
OnePerson :提示 1.需要一个结束的标记 2.定义一把锁
packet anotherPerson
SendTask:专门用来做发送数据
ReceiveTask :专门用来接收数据
利用Runnable的方式去做
AnotherPerson :提示 1.需要一个结束的标记 2.定义一把锁
使用同一个DatagramSocket 作为成员变量 利用构造函数的方式去处理
2.做一个聊天室
ip改成广播地址
3.PPT上的剩余没有演示的做练习
图片
客户端
package day07.Work.work3.SendPicture;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class ClientPicture {
public static void main(String[] args) throws IOException {
System.out.println("上传图片客户端启动...");
//1、创建socket
Socket s = new Socket("192.168.5.18", 13002);
//2、读取源图片
File picFile = new File("C:\\Users\\11924\\Pictures\\樱木花道.jpg");
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(picFile));
//3、目的:socket输出流,发送到服务端
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1)
{
out.write(buf, 0, len);
}
//告诉服务端 图片发送完成,不要在等着读了
s.shutdownOutput();
//读取上传成功字样
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String info = in.readLine();
System.out.println(info);
//关闭
fis.close();
s.close();
}
}
服务端
package day07.Work.work3.SendPicture;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SeverPicture {
public static void main(String[] args) throws IOException {
System.out.println("上传图片服务端启动...");
// 创建ServerSocket
ServerSocket ss = new ServerSocket(13002);
while (true) {
// 获取客户端
Socket s = ss.accept();
// 实现多个客户端并发上传,服务器端必须启动做个线程来完成
new Thread(new UploadPic(s)).start();
}
}
}
class UploadPic implements Runnable {
private Socket s;
public UploadPic(Socket s) {
super();
this.s = s;
}
@Override
public void run() {
try {
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "连接中...");
// 写图片数据到文件的输出流
File dir = new File("C:\\Users\\11924\\Pictures");
// 为了避免重名覆盖,通过给重名文件进行编号
int count = 1;
File picFile = new File(dir, ip + "(" + count + ")" + ".jpg");
while (picFile.exists()) {
count++;
picFile = new File(dir, ip + "(" + count + ")" + ".jpg");
}
FileOutputStream fos = new FileOutputStream(picFile);
// 读取客户端发来的数据
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 给客户端一个回馈信息
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
out.write("上传成功!"); // 写完需要刷新一下,或者关闭流
// 关闭资源
out.close();
fos.close();
s.close();
} catch (Exception e) {
}
}
}

文字输入文本输出
文本输入文字输出
宋红康
1.一个IP对应着哪个类的一个对象?InetAddress.
实例化这个类的两种方式是?。
InetAddress.getByName(String host)
InetAddress.getLocalHost();//获取本地ip两个常用的方法是?。
getHostName();
getHostPort();
2.传输层的TCP协议和UDP协议的主要区别是?。
TCP:可靠(三次握手);进行大数据量传输;效率低
UDP:不可靠,只发送;只是以数据报传输,数据大小限定64;效率高
3.什么是URL,你能写一个URL吗?
URL:统一资源定位符
URL url=new URL (“http://192.168.14.100:8080/examples/hello. txt”);
4.谈谈你对对象序列化机制的理解。
序列化:
反序列化:
5.对象要想实现序列化,需要满足哪几个条件。
1.实现接:Serializable标识接口。
2.对象所在的类提供常量:序列版本号【serioUID???】
3.要求对象的属性也必须是可序列化的。(基本数据类型、string:本身就已经是可序列化
day07
作业
upd发送文件
package day07.heima;
import java.io.IOException;
import java.net.*;
public class UDPSend {
public static void main(String[] args) throws IOException {
//创建发送端对象
DatagramSocket ds = new DatagramSocket();
//创建数据并打包
//DatagramPacket(byte[] buf, int length, InetAddress address, int port)
byte[] bytes="hello ,udp ,我来了".getBytes();
/**int length=bytes.length;
InetAddress address = InetAddress.getByName("潘晨");
int port =10086;
DatagramPacket dp = new DatagramPacket(bytes, length, address, port);*/
DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("潘晨"), 10086);
//调用DatagramSocket()对象并发送数据
ds.send(dp);
//关闭发送端
ds.close();
}
}
接收
package day07.heima;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPReceive {
public static void main(String[] args) throws IOException {
//1:建立udp的socket服务,要指定监听的端口,如果监听到发送来的数据包,就获取。创建接收端Scoket对象【DatagramScoket】
DatagramSocket ds = new DatagramSocket(10086);
//2.新建一个字节数组,利用它才创建新的数据包
byte[]bytes=new byte[2014];
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
//3:通过receive方法接收数据,将收到的数据存储到自己新建的数据包对象中
ds.receive(dp);
//4:拆包,通过数据包对象的功能来完成对接收到数据进行解析.
byte[] datas = dp.getData();
//获取接受数据长度
int len=dp.getLength();
String datastring=new String(datas,0,len);
System.out.println("数据是"+datastring);
//5.结束资源
ds.close();
}
}
day07_network
1.利用多线程的方式去改造UDP v3版本代码
packet oneperson
SendTask:专门用来做发送数据
ReceiveTask :专门用来接收数据
利用Runnable的方式去做
OnePerson :提示 1.需要一个结束的标记 2.定义一把锁
packet anotherPerson
SendTask:专门用来做发送数据
ReceiveTask :专门用来接收数据
利用Runnable的方式去做
AnotherPerson :提示 1.需要一个结束的标记 2.定义一把锁
使用同一个DatagramSocket 作为成员变量 利用构造函数的方式去处理
2.做一个聊天室
ip改成广播地址
3.PPT上的剩余没有演示的做练习
图片
客户端
package day07.Work.work3.SendPicture;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class ClientPicture {
public static void main(String[] args) throws IOException {
System.out.println("上传图片客户端启动...");
//1、创建socket
Socket s = new Socket("192.168.5.18", 13002);
//2、读取源图片
File picFile = new File("C:\\Users\\11924\\Pictures\\樱木花道.jpg");
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(picFile));
//3、目的:socket输出流,发送到服务端
OutputStream out = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1)
{
out.write(buf, 0, len);
}
//告诉服务端 图片发送完成,不要在等着读了
s.shutdownOutput();
//读取上传成功字样
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String info = in.readLine();
System.out.println(info);
//关闭
fis.close();
s.close();
}
}
服务端
package day07.Work.work3.SendPicture;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SeverPicture {
public static void main(String[] args) throws IOException {
System.out.println("上传图片服务端启动...");
// 创建ServerSocket
ServerSocket ss = new ServerSocket(13002);
while (true) {
// 获取客户端
Socket s = ss.accept();
// 实现多个客户端并发上传,服务器端必须启动做个线程来完成
new Thread(new UploadPic(s)).start();
}
}
}
class UploadPic implements Runnable {
private Socket s;
public UploadPic(Socket s) {
super();
this.s = s;
}
@Override
public void run() {
try {
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "连接中...");
// 写图片数据到文件的输出流
File dir = new File("C:\\Users\\11924\\Pictures");
// 为了避免重名覆盖,通过给重名文件进行编号
int count = 1;
File picFile = new File(dir, ip + "(" + count + ")" + ".jpg");
while (picFile.exists()) {
count++;
picFile = new File(dir, ip + "(" + count + ")" + ".jpg");
}
FileOutputStream fos = new FileOutputStream(picFile);
// 读取客户端发来的数据
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 给客户端一个回馈信息
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
out.write("上传成功!"); // 写完需要刷新一下,或者关闭流
// 关闭资源
out.close();
fos.close();
s.close();
} catch (Exception e) {
}
}
}

文字输入文本输出
文本输入文字输出
宋红康
1.一个IP对应着哪个类的一个对象?InetAddress.
实例化这个类的两种方式是?。
InetAddress.getByName(String host)
InetAddress.getLocalHost();//获取本地ip两个常用的方法是?。
getHostName();
getHostPort();
2.传输层的TCP协议和UDP协议的主要区别是?。
TCP:可靠(三次握手);进行大数据量传输;效率低
UDP:不可靠,只发送;只是以数据报传输,数据大小限定64;效率高
3.什么是URL,你能写一个URL吗?
URL:统一资源定位符
URL url=new URL (“http://192.168.14.100:8080/examples/hello. txt”);
4.谈谈你对对象序列化机制的理解。
序列化:
反序列化:
5.对象要想实现序列化,需要满足哪几个条件。
1.实现接:Serializable标识接口。
2.对象所在的类提供常量:序列版本号【serioUID???】
3.要求对象的属性也必须是可序列化的。(基本数据类型、string:本身就已经是可序列化
day08_reflect
1.设计一个方法如下,要求该方法能修改任意对象中,指定成员变量的值
public class Work1 {
/*
- @param targetObj 要修改成员变量值的目标对象
- @param fieldName 对象中要修改的成员变量的名字
- @param newValue 要修改成员变量值的新值
*/
public static void setAll(Object targetObj, String fieldName, Object newValue) {
}
package day08.work.work01;
/**
* @author panda
* @description:修改任意对象中指定成员变量的值
* @date 2021/2/26 17:17
*/
import java.lang.reflect.Field;
/**
*
• @param targetObj 要修改成员变量值的目标对象
• @param fieldName 对象中要修改的成员变量的名字
• @param newValue 要修改成员变量值的新值
*/
public class Work1 {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Fruit fruit1 = new Fruit("apple", 20);
System.out.println(fruit1.toString());
setAll(fruit1,"price",30);
}
public static void setAll(Object targetObj, String fieldName, Object newValue) throws IllegalAccessException, NoSuchFieldException {
//创建要修改成员变量值的目标对象
Class targetObjClass = targetObj.getClass();
//对象中要修改的成员变量的名字
Field declaredField = targetObjClass.getDeclaredField(fieldName);
//解决权限问题
declaredField.setAccessible(true);
//在指定对象上修改成员变量值的新值
declaredField.set(targetObj, newValue);
//验证targetObj的值已经改变
System.out.println(targetObj);
}
}
class Fruit{
private String name;
private int price;
Fruit(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Fruit{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
2.完成如下方法,要求该方法能调用,指定配置文件中,指定类中指定的普通成员方法(无参方法)
假设指定类中一定有默认构造方法
public class Work2 {
/**
*
* @param configFilePath 表示配置文件的路径
*/
public void callTargetMethod(String configFilePath) {
}
package day08.work.work02;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
/**
* @author panda
* @description:
* @date 2021/2/26 22:36
*/
public class Work2_2 {
public void callTargetMethod(String configFilePath)
throws IOException, ClassNotFoundException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException,
InstantiationException {
//🔺1.读取配置文件信息,将去读取到我们的Properties对象中
Properties properties = loadConfigFileInfo(configFilePath);
//🔺2.从Properties对象中,获取指定类的全类名和指定的方法名
String className = properties.getProperty("className");
String methodName = properties.getProperty("methodName");
//通过全类名,获取全类名所指定的类的类型信息(访问对应的Class)
Class targetClass = Class.forName(className);
//🔺利用反射,从targetClass中获取目标方法的method对象
Method targetMethod = targetClass.getDeclaredMethod(methodName);
//🔺绕过jvm检查机制
targetMethod.setAccessible(true);
//🔺利用反射创建目标对象(Constructor对象.newInstance(),利用无参构造方法)
Constructor declaredConstructor = targetClass.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
//🔺利用反射,创建目标对象
Object targetObj = declaredConstructor.newInstance();
//🔺在目标对象上,调用执行Method对象表示的方法,并传递参数(Method对象.invoke(目标对象))
targetMethod.invoke(targetObj);
}
private Properties loadConfigFileInfo(String configFilePath) throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream(configFilePath));
return properties;
}
}
package day08.work.work02;
import sun.font.EAttribute;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
/**
* @author panda
* @description:该方法调用指定配置文件中,指定类的普通成员方法(无参方法)
* @date 2021/2/26 17:19
*/
public class Work2 {
public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
//配置文件中放全限定类名
callTargetMethod(
"C:\\Users\\11924\\IdeaProjects\\WangDaoMid\\src\\day08\\work\\work02\\config.properties",
"person","person.eat");
}
//方法一通过地址获取类,并且获取对象
public static void callTargetMethod(String configFilePath,String targetClassName,String targetMethodName)
throws IOException, ClassNotFoundException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException,
InstantiationException {
//1.读取配置文件信息,将去读取到我们的Properties对象中
Properties properties = new Properties();
properties.load(new FileInputStream(configFilePath));
//2.从Properties对象中,获取指定类的全类名和指定的方法名
String className = properties.getProperty(targetClassName);
String methodName = properties.getProperty(targetMethodName);
//通过全类名,获取全类名所指定的类的类型信息(访问对应的Class)className是全限定类名
Class targetClass = Class.forName(className);
//利用反射,从targetClass中获取目标方法的method对象
Method targetMethod = targetClass.getDeclaredMethod(methodName);
//绕过jvm检查机制
targetMethod.setAccessible(true);
//利用反射创建目标对象(Constructor对象.newInstance(),利用无参构造方法)
Constructor declaredConstructor = targetClass.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
//利用反射,创建目标对象
Object targetObj = declaredConstructor.newInstance();
//在目标对象上,调用执行Method对象表示的方法,并传递参数(Method对象.invoke(目标对象))
targetMethod.invoke(targetObj);
}
}
配置文件
fruit=day08.work.work02.Fruit
person=day08.work.work02.Person
person.eat=eat
day09_annotation&gc
1. 自定义注解,该注解用来描述,方法运行所需的时间上限(用long类型的数据表示时间,单位为ms),
然后,自定义注解处理器,运行加了运行时间上限注解的方法,判断方法的运行时间,
是否超出了注解中规定的时间上限,如果超过,则返回true,未超过返回false
package day09.work;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author panda
* @description:
* @date 2021/2/27 16:42
*/
public class MyWork {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
Class<TestTimeLimit> testTimeLimitClass = TestTimeLimit.class;
Method run = testTimeLimitClass.getDeclaredMethod("run");
run.setAccessible(true);
//判断是否有目标类型的注解、
TimeLimit runAnnotation = run.getAnnotation(TimeLimit.class);
//获取注解实例的属性值
long timeLimit = runAnnotation.timeLimit();
//开始时间
long start = System.currentTimeMillis();
//测试程序执行
TestTimeLimit test= testTimeLimitClass.newInstance();
run.invoke(test);
//结束时间
long end=System.currentTimeMillis();
long time=end-start;
if(time>timeLimit){
System.out.println(true);
throw new IllegalArgumentException("运行时间过长" + time);
}
else {
System.out.println(false);
}
}
}
//元注解表示runtime运行时注解存在
@Retention(RetentionPolicy.RUNTIME)
//元注解去定义注解的作目标
@Target({ElementType.METHOD})
@interface TimeLimit{
long timeLimit();
}
//设置时间和测试运行方法
class TestTimeLimit{
@TimeLimit(timeLimit = 200)
public static void run()throws InterruptedException{
Thread.sleep(500);
}
}
day14_exception
- 定义三种新类型的异常。
写一个类,在该类的三个方法中抛出三种不同的异常。
然后在main方法中调用这个类的不同方法,尝试用try catch捕获你写的异常。
```java public class Work2 {
public static void main(String[] args) {
ExceptionGenerator exceptionGenerator = new ExceptionGenerator();
//处理第一种自定义编译时异常
try {
exceptionGenerator.genFirstException();
} catch (MyFirstException e) {
e.printStackTrace();
}
//处理第二种自定义运行时异常
try {
exceptionGenerator.genSecondException();
} catch (Exception e) {
e.printStackTrace();
}
//处理第三种自定义编译时异常
try {
exceptionGenerator.genThirdException();
} catch (MyThirdException e) {
e.printStackTrace();
}
}
}
class ExceptionGenerator {
//抛出第一种编译时异常
public void genFirstException() throws MyFirstException {
throw new MyFirstException("第一种编译时类型的异常");
}
//抛出第二种运行时异常
public void genSecondException() {
throw new MySecondException("第二种运行时类型的异常");
}
//抛出第二种编译时异常
public void genThirdException() throws MyThirdException {
throw new MyThirdException("第三种编译时类型的异常");
}
}
/*
第一种自定义编译时异常
*/
class MyFirstException extends Exception {
public MyFirstException(String msg) {
super(msg);
}
}
/*
第二种自定义运行时异常
*/
class MySecondException extends RuntimeException {
public MySecondException(String msg) {
super(msg);
}
}
/*
第三种自定义编译时异常
*/
class MyThirdException extends Exception {
public MyThirdException(String msg) {
super(msg);
}
} ```
2.1. 递归删除目录
目录结构为如下(尽量不要在c盘中测试哈)<br /> firstLevel目录中,包含一个secondLevel目录和a1.txt和b1.java文件<br /> secondLevel目录中包含dir1和dir2两个目录,和a2.txt和b2.java文件<br /> dir1目录中包含a3.txt和b3.java文件<br /> dir2目录是一个空目录
要求删除firstLevel目录
思路:
- 获取目录的下的所有File对象(包括文件和文件夹)
- 判断,如果是一个空目录或者file对象不是一个目录而是文件
- 直接删除
- 程序执行到这里,那么一定是一个目录,且不是空目录
- 遍历获取的file数组
- 如果这个file对象仍然是一个目录,递归删除该目录
- 如果这个file对象是文件,直接删除
- 最后不要忘记删除已经是空目录的当前目录
先看思路,逐步求解
实在不懂,看参考答案


