Java基础程序设计结构
在 Math 类中,为了达到最快的性能,所有的方法都使用计算机浮点单元中的例程,如果得到一个完全可预测的结果比运行速度更重要的话,那么就应该使用StrictMath类,它使用 “*发布的 Math 库 ” ( fdlibm ) 实现算法 , 以确保在所有平台上得到相同的结果。
不要在boolean与任何数值类型之间进行强制类型转换,防止错误
不要用== 运算符测试字符串的相等性:只有字符串常量是共享的, 而 + 或 substring等操作产生的结果并不是共享的。
不要使用 char 类型,太过底层,UTF-16需要两个代码单元,用charAt会有问题。
在循环中 , 检测两个浮点数是否相等需要格外小心 。
从 Java SE 7 开始 , case 标签还可以是字符串字面量
带标签的break
int j = 10;
breakpoint:
for (int i=0;i<10;i++){
while (j-->0){
if(j==5){
break breakpoint;
}
}
}
System.out.println(j);
可以将标签应用到任何语句中 , 甚至可以应用到 if 语句或者块语句中
只能跳出语句块,而不能跳入语句块
Biglnteger 类实现了任意精度的整数运算 , BigDecimal 实现了任意精度的浮点数运算
数组长度为 0 与 null 不同
Arrays.copyOf :一个数组的所有值拷贝到一个新的数组中
运行时常量池从方法区中分配
Java Stream
Map<Integer, List<Integer>> map = random.ints(size, 0, bound).boxed().sorted().collect(Collectors.groupingBy(value->value/10));
Java的网络通信
XML操作
定义
XML 指可扩展标记语言
XML 被设计用来传输和存储数据。
语法规则
- 所有 XML 元素都须有关闭标签
- XML 标签对大小写敏感
- XML 必须正确地嵌套
- XML 文档必须有根元素
- XML 的属性值须加引号
- 在 XML 中,空格会被保留
Json操作
JavaScript对象表示法(JavaScript Object Notation),是轻量级的文本数据交换格式
JSON 是存储和交换文本信息的语法。类似 XML。
JSON 比 XML 更小、更快,更易解析。
public static void readJson(){
try {
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(new FileReader("test.json"));
System.out.println(jsonObject.get("cat").getAsString());
System.out.println(jsonObject.get("pop").getAsBoolean());
JsonArray array = jsonObject.get("book").getAsJsonArray();
for (int i=0;i<array.size();i++) {
System.out.println("====");
JsonObject subJson = array.get(i).getAsJsonObject();
System.out.println(subJson.get("id").getAsInt());
System.out.println(subJson.get("name").getAsString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
HTTP操作
使用http的Get读取网络数据
public static void doGet(){
URL url = null;
try {
url = new URL("http://www.dengyouquan.cn");
URLConnection connection = url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
try(BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));) {
String line = null;
while ((line=reader.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
使用http的Post与网络通信
public static void doPost() {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL("http://www.dengyouquan.cn");
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("encoding", "UTF-8");//添加请求属性
connection.setDoInput(true);//允许输入
connection.setDoOutput(true);//允许输出
connection.setRequestMethod("POST");//POST请求
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (connection == null)
return;
//writer与reader顺序一致
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
) {
writer.write("?p=6");
writer.flush();
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
使用HttpClient进行Get通信
public static void doHttpClientGet(){
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://www.dengyouquan.cn");
try (CloseableHttpResponse httpResponse = (CloseableHttpResponse) httpClient.execute(httpGet);){
HttpEntity entity = httpResponse.getEntity();
if(entity!=null){
String entityStr= EntityUtils.toString(entity,"utf-8");
System.out.println(entityStr);
}
} catch (IOException e) {
e.printStackTrace();
}
}
使用HttpClient进行Post通信
public static void doHttpClientPost(){
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://www.dengyouquan.cn");
List<BasicNameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("p","6"));
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println(EntityUtils.toString(httpEntity,"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Socket操作
Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。
HTTP1.0默认是短连接,无状态的.
Http1.1默认是长连接
半包:接受方没有接受到一个完整的包,只接受了部分;
粘包:发送方发送的多个包数据到接收方接收时粘成一个包。
TCP:流,会有半包和粘包
UDP:数据包,无半包和粘包
ServerSocket和Socket
使用Socket时用BufferedReader会阻塞
socket通信服务器端
Socket编程中,尽量用PrintWriter取代BufferedWriter
PrintWriter的println方法自动添加换行,BufferedWriter需要显示调用newLine方法
PrintWriter的print、println方法可以接受任意类型的参数
PrintWriter和BufferedWriter的使用区别
Scanner的平均耗时是BufferedReader的10倍左右
java Scanner与BufferedReader读取键盘输入性能比较
推荐Scanner
java控制台输入 InputStreamReader与Scanner ,Console 区别
public class ServerSocket1 {
private static final int PORT = 8888;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("服务器已启动...");
int j = 0;
while (j++<Integer.MAX_VALUE){
Socket socket = serverSocket.accept();
new Thread(new ServerSocketHandler(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerSocketHandler implements Runnable {
private Socket socket;
ServerSocketHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try(BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))){
String line = null;
System.out.println("服务器已连接...");
boolean exit = false;
while (!exit){
System.out.println("等待消息");
String msg = reader.readLine();
switch (msg){
case "":
continue;
case "date":
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("localDateTime:"+localDateTime);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
writer.write(dateTimeFormatter.format(localDateTime)+System.lineSeparator());
break;
case "exit":
System.out.println("server close...");
writer.write("exit"+System.lineSeparator());
exit = true;
break;
default:
writer.write("commend not found!"+System.lineSeparator());
}
writer.flush();
}
} catch (IOException e) {
System.out.println("客户端异常退出。。。");
}
}
}
socket通信客户端
public class ClientSocket implements Runnable {
private static final String ADDRESS = "127.0.0.1";
private static final int PORT = 8888;
public static void main(String[] args) {
new Thread(new ClientSocket()).start();
}
@Override
public void run() {
try(Socket socket= new Socket(ADDRESS,PORT);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner scanner = new Scanner(System.in);){
boolean exit = false;
System.out.println("客户端已连接...");
while (!exit) {
writer.write(scanner.nextLine() + System.lineSeparator());
writer.flush();
String line = reader.readLine();
System.out.println("客户端收到消息:"+line);
if(line.equals("exit")){
exit = true;
}
}
} catch (IOException e) {
System.out.println("无服务器");
}
}
}