关于CodeJava的学习笔记——10
一、URL
1、读取网页数据
首先导入import java.net.*;
通过URL访问网页,数据读取到url,然后使用InputStreamReader
URL url = new URL("https://www.etoak.com/static/video/video/four.mp4");
import java.net.*;
import java.io.*;
import java.util.*;
public class TestURLMax{
public static void main(String[] args)throws Exception{
http://old.etoak.com/assets/etoak.json
System.out.println("上面是接口地址..");
URL url = new URL("http://old.etoak.com/assets/etoak.json");
URLConnection uc = url.openConnection();
InputStream is = uc.getInputStream();
InputStreamReader r = new InputStreamReader(is,"utf-8");
BufferedReader br = new BufferedReader(r);
String str;
Map<String,List<String>> map = new HashMap<>();
while((str = br.readLine())!=null){
if(str.contains("name") && str.contains("city")){
// { "id": "ET002","name": "王磊","price": "¥14000","city": "杭州","company": "杭州华数传媒" },
String name = str.substring(str.indexOf("name")+8,str.indexOf("price")-3);
String city = str.substring(str.indexOf("city")+8,str.indexOf("company")-3);
if(map.containsKey(city)){
List<String> list = map.get(city);
list.add(name);
}else{
List<String> list = new ArrayList<>();
list.add(name);
map.put(city,list);
}
}
}
br.close();
{
Map<List<String>,String> temp = new TreeMap<>((a,b) -> a.size() == b.size() ? 1 : Integer.compare(b.size(),a.size()));
map.forEach((k,v) -> temp.put(v,k));
temp.entrySet().stream().limit(5).forEach((e) -> {
List<String> k = e.getKey();
String v = e.getValue();
System.out.println(v+" : "+k.size());
k.forEach((name) -> System.out.print(" "+name));
System.out.println();
});
}
}
}
2、下载网络资源
1、下载视频
import java.net.*;
import java.io.*;
public class TestURLPlus{
public static void main(String[] args)throws Exception{
URL url = new URL("https://www.etoak.com/static/video/video/four.mp4");
URLConnection uc = url.openConnection();
InputStream is = uc.getInputStream();
int total = uc.getContentLength();//得到资源的内容长度
int current = 0;//当前已经完成的字节数
int lastPercent = -1;//最近显示过的百分比
FileOutputStream fos = new FileOutputStream("etoak.mp4");
byte[] data = new byte[128<<10];
int len;
while((len = is.read(data))!=-1){
fos.write(data,0,len);
current+=len;
int percent = (int)(current * 100L / total);
if(percent != lastPercent){
System.out.print("\r已经完成"+percent+"%");
lastPercent = percent;
}
}
fos.close();
is.close();
}
}
2、下载图片
import java.net.*;
import java.io.*;
public class TestURL{
public static void main(String[] args)throws Exception{
URL url = new URL("http://old.etoak.com/assets/images/zkcs.png");
URLConnection uc = url.openConnection();//打开连接
InputStream is = uc.getInputStream();
FileOutputStream fos = new FileOutputStream("jay.png");
byte[] data = new byte[16384];
int len;
while((len = is.read(data))!=-1){
fos.write(data,0,len);
}
fos.close();
is.close();
}
}
二、BigOne
该项目的需求是,在一堆消费数据中,有很多消费为0 的订单,那么在计算最终金额的时候,我们也会计算金额为0的部分,那么他们的名字就会存在Map中,那么最终我们不希望,这些吗,没有任何消费的人进入展示的列表里面,那么就需要我们进行遍历删除。考察的主要是前面的综合知识。
import java.util.*;
import java.io.*;
public class Exec2{
static Map<String,List<Person>> map = new HashMap<>();
public static void main(String[] args)throws Exception{
FileInputStream file = new FileInputStream("data.txt");
InputStreamReader r = new InputStreamReader(file,"utf-8");
BufferedReader br = new BufferedReader(r);
String str;
a:while((str = br.readLine()) != null){
String ax = str.substring(0,2);
String bx = str.substring(2,4);
int cx = Integer.valueOf(str.substring(6,7));
//System.out.println(bx);
if(map.containsKey(ax)){
for(Person p : map.get(ax)){
if(p.name.equals(bx)){
p.addcost(cx);
continue a;
}
}
Person p = new Person(bx,cx);
map.get(ax).add(p);
}else{
List<Person> list = new ArrayList<>();
Person p = new Person(bx,cx);
list.add(p);
map.put(ax,list);
}
}
/**
map.forEach((k,v) -> {
System.out.println(k);
v.forEach(x -> System.out.println(" " + x));
});
Map<List<Person>,String> temp = new TreeMap<>();
map.forEach((k,v) -> {
temp.put(v,k);
});
*/
map.forEach((k,v) -> {
System.out.println(k);
for(Iterator<Person> car = v.iterator(); car.hasNext(); ){
Person x = car.next();//取出遍历的元素
if(x.cost == 0)car.remove();
}
v.forEach(x -> System.out.println(" " + x));
});
//System.out.println(map);
}
}
class Person{
String name;
int cost;
public Person(String name,int cost){
this.name = name;
this.cost = cost;
}
public void addcost(int ax ){
cost = cost + ax;
}
public String toString(){
return name + " 花费 " + cost;
}
}
三、服务端与客户端
练习1
client
import java.io.*;
import java.net.*;
import javax.swing.*;
public class TestClient01{
public static void main(String[] args)throws Exception{
while(true){
String str = JOptionPane.showInputDialog(null,"请输入内容:");
if("88".equals(str)){
break;
}
Socket skt = new Socket("192.168.31.236",17888);
OutputStream os = skt.getOutputStream();
OutputStreamWriter w = new OutputStreamWriter(os,"GBK");
PrintWriter pw = new PrintWriter(w,true);
pw.println(str);
pw.close();
skt.close();
}
}
}
server
import java.net.*;
import java.io.*;
import java.util.concurrent.*;
public class TestServer01{
public static void main(String[] args)throws Exception{
ExecutorService es = Executors.newFixedThreadPool(5);
ServerSocket server = new ServerSocket(17888);//1024
boolean isRunning = true;
while(isRunning){
Socket skt = server.accept();
ServerThread st = new ServerThread(skt);
es.submit(st);
}
server.close();
es.shutdown();
}
}
class ServerThread extends Thread{
Socket skt;
public ServerThread(Socket skt){
this.skt = skt;
}
@Override
public void run(){
try{
InputStream is = skt.getInputStream();
InputStreamReader r = new InputStreamReader(is,"GBK");
BufferedReader br = new BufferedReader(r);
String str = br.readLine();
String ip = skt.getInetAddress().toString();
System.out.println(ip + " : " + str);
br.close();
skt.close();
}catch(Exception e){
System.out.println(skt.getInetAddress() +"出事了");
//e.printStackTrace();
}
}
}
练习2
client
import java.io.*;
import java.net.*;
public class TestClient02{
public static void main(String[] args)throws Exception{
Socket skt = new Socket("192.168.31.236",17666);
InputStream is = skt.getInputStream();
FileOutputStream fos = new FileOutputStream("okk.jpg");
byte[] data = new byte[16384];
int len;
while((len = is.read(data))!=-1){
fos.write(data,0,len);
}
fos.close();
is.close();
}
}
server
import java.net.*;
import java.io.*;
import java.util.concurrent.*;
public class TestServer02{
public static void main(String[] args)throws Exception{
ExecutorService es = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(17666);
boolean isRunning = true;
while(isRunning){
Socket skt = server.accept();
EtoakThread et = new EtoakThread(skt);
es.submit(et);
}
server.close();
es.shutdown();
}
}
class EtoakThread implements Runnable{
Socket skt;
public EtoakThread(Socket skt){
this.skt = skt;
}
@Override
public void run(){
try{
FileInputStream fis = new FileInputStream("jay.jpg");
OutputStream os = skt.getOutputStream();
byte[] data = new byte[16384];
int len;
while((len = fis.read(data))!=-1){
os.write(data,0,len);
}
os.close();
fis.close();
System.out.println(skt.getInetAddress() + " 到此一游~");
}catch(Exception e){
e.printStackTrace();
}
}
}
练习3
client
import javax.swing.*;
import java.net.*;
import java.io.*;
/*
1.采集用户数据
2.校验数据是否合法
3.连接后台服务器
4.将采集到的数据发送给服务器
5.接收服务器处理完成的结果
6.将结果展现给用户
*/
public class TestClient03{
public static void main(String[] args)throws Exception{
String name = JOptionPane.showInputDialog(null,"请输入姓名:");
if(name == null || name.trim().length() == 0){
JOptionPane.showMessageDialog(null,"手呢?!");
return;
}
Socket skt = new Socket("192.168.31.236",12666);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(skt.getOutputStream(),"UTF-8"),true);
pw.println(name);
BufferedReader br = new BufferedReader(new InputStreamReader(skt.getInputStream(),"GBK"));
String result = br.readLine();
br.close();
pw.close();
skt.close();
JOptionPane.showMessageDialog(null,name+" : " + result);
}
}
server
import java.util.*;
import java.net.*;
import java.io.*;
import java.util.concurrent.*;
public class TestServer03{
public static void main(String[] args)throws Exception{
ExecutorService es = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(12666);
boolean isRunning = true;
while(isRunning){
Socket skt = server.accept();
ComputeThread ct = new ComputeThread(skt);
es.submit(ct);
}
server.close();
es.shutdown();
}
}
class ComputeThread implements Callable<String>{
Socket skt;
public ComputeThread(Socket skt){
this.skt = skt;
}
@Override
public String call()throws Exception{
//1.接 接收客户端发送来的名字(字符串)
InputStream is = skt.getInputStream();
InputStreamReader r = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(r);
String name = br.readLine();
//2.化 对数据进行运算处理 X.compute();
String result = X.compute(name);
//3.发 接处理结果(字符串)发还给客户端
OutputStream os = skt.getOutputStream();
OutputStreamWriter w = new OutputStreamWriter(os,"GBK");
PrintWriter pw = new PrintWriter(w,true);
pw.println(result);
pw.close();
br.close();
skt.close();
System.out.println(skt.getInetAddress() + " -> "+ name + " -> " + result);
return null;
}
}
class X{
public static String compute(String name){
if(name.contains("吴") || name.toLowerCase().contains("v"))
return "天机不可泄露";
String[] data = {"牢狱之灾","命运多舛","平平淡淡","大富大贵","天命之子"};
int hash = name.hashCode();
long now = System.currentTimeMillis() / (24L*60*60*1000);
now = now * 17 / 11 * 23 / 13;
hash += now;
hash = Math.abs(hash);
int x = hash % data.length;
return data[x];
}
}