文章目录
产生随机数
1.Random()构造一个新的随机数生成器
2.Int nextInt(int n) 返回一个0~n-1之间的随机数
获取当前时间、日期,上一周、下一周等
获取本周周一日期
Date now = new Date();
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR),
cal.get(Calendar.MONDAY),
cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
starttime = sd.format(cal.getTime());
获取下周一日期
Calendar caldar = Calendar.getInstance();
caldar.setTime(cal.getTime());
caldar.add(Calendar.DAY_OF_WEEK, 7);
endtime = sd.format(caldar.getTime());
获取本月日期
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
获取上个月日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
String endtime = sdf.format(calendar.getTime());
System.out.println(endtime);
获取下一年
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
Calendar cale = Calendar.getInstance();
cale.add(Calendar.YEAR, 1);
// 设置下一个月为查询范围的终止时间2018
endtime = sdf.format(cale.getTime());
*获取当前日期1000天后的日期
LocalDate newYearsEve=LocalDate.of(1992,12,31);
Int year =newYearsEve.getYear(); //获取年
Int month=newYearsEve.getMonthValue(); //获取月
Int day=newYearsEve.getDayOfMonth(); //获取日
LocalDate aThousandDaysLater =newYearsEve.plusDays(1000); //1000天以后的日期
Year =aThousandDaysLater.getYear(); //2002
Month=aThousandDaysLater.getMonthValue(); //09
Day=aThousandDaysLater.getDayOfMonth(); //26
基本数据类型如何比较是否相等、引用类型如何比较是否相等
基本类型(byte、short、int、float、double)可以用==进行比较
引用类型(Byte、Short、Integer、Float、Double)则不能,需要用.compareTo(…)进行比较
重定向输出流实现程序日志
1.代码
package Test;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.net.StandardSocketOptions;
public class Test01 {
public static void main(String[] args) {
try {
//保存原输出流
PrintStream out = System.out;
//创建文件输出流
PrintStream ps=new PrintStream("./log.txt");
//设置使用新的输出流
System.setOut(ps);
//定义整型变量
int age=18;
System.out.println("年龄变量成功定义,初始值为18");
//定义字符串变量
String sex="女";
System.out.println("性别变量成功定义,初始值为女");
String info="这是个"+sex+"孩子,应该有"+age+"岁了。";
System.out.println("整合两个变量为info字符串变量,其结果是:"+info);
//恢复原有的输出流
System.setOut(out);
System.out.println("程序运行完毕,请查看日志文件。");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
技术要点:
setOut()方法
该方法用于重新分配System类的标准输出流
setErr()方法
该方法将重新分配System类的标准错误输出流
setIn()方法
该方法将重新设置System类的标准输入流
Scanner
从控制台接受输入字符
// 构建一个Scanner对象,并与“标准输入流”System.in关联
Scanner in=new Scanner(System.in);
//使用,获取输入的内容
System.out.print(“What is your name”);
String name=in.nextLine(); //nextLint()读取输入行,当其中可能包含空格
in.next(); //读取一个单词(以空白符作为分隔符)
in.nextInt(); //读取一个整数
in.nextDouble();//读取一个浮点数
数组
数组拷贝Arrays.copyOf()
//第二个参数是新数组的长度。
int[] copiedLuckyNumbers=Arrays.copyOf(luckNumbers,luckyNumbers.length);
注意:
①两个变量将引用同一个数组。
②如果数组元素是数值型,那么多余的元素将被赋值为0,如果数组元素是布尔型,则将赋值为false。相反,如果长度小于原始数组的长度,则只拷贝最前面的数据元素
反转数组
【方法一】使用集合个工具类: Collections.reverse(ArrayList) 将数组进行反转:
import java.util.ArrayList;import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E");
System.out.println("反转前排序: " + arrayList);
Collections.reverse(arrayList);
System.out.println("反转后排序: " + arrayList);
}
}
反转前排序: [A, B, C, D, E]
反转后排序: [E, D, C, B, A]
【方法二】使用集合ArrayList实现反转:
【方法三】直接使用数组实现反转,即,反转后数组的第一个元素等于源数组的最后一个元素:
方法二和方法三的实现代码如下:
package javatest2;
import java.util.ArrayList;
public class JavaTest2 {
public static void main(String[] args) {
String[] Array = { "a", "b", "c", "d", "e" };
reverseArray1(Array);// 使用集合ArrayList实现反转
for (int j = 0; j < Array.length; j++) {
System.out.print(Array[j] + " ");
}
System.out.print("\n");
String[] temp = reverseArray2(Array);// 直接使用数组实现反转
for (int j = 0; j < temp.length; j++) {
System.out.print(Array[j] + " ");
}
}
/*
* 函数:reverseArray1和reverseArray2
* 功能:实现 数组翻转
* 例如:{'a','b','c','d'}变成{'d','c','b','a'}
*/
private static void reverseArray1(String[] Array) {
ArrayList<String> array_list = new ArrayList<String>();
for (int i = 0; i < Array.length; i++) {
array_list.add(Array[Array.length - i - 1]);
}
Array = array_list.toArray(Array);
}
private static String[] reverseArray2(String[] Array) {
String[] new_array = new String[Array.length];
for (int i = 0; i < Array.length; i++) {
// 反转后数组的第一个元素等于源数组的最后一个元素:
new_array[i] = Array[Array.length - i - 1];
}
return new_array;
}
}
循环
for、while循环、switch中断控制流程语句
标签必须放在希望跳出的最外层循环之前,并且必须紧跟一个冒号
Scanner in=new Scanner(System.in);
Int n;
Read_data:
While(....){
....
for(....){
System.out.print("Enter a number >=0: ");
n=in.nextInt();
If(n<0){
Break read_data;
}
}
}
退出双层for循环
lable:
for(元素变量x:遍历对象obj){
for(元素变量y:遍历对象objy){
if(条件表达式){
break lable;
}
}
}
字符串
拼接字符串
①用“+”号连接
②用静态join方法
String all=String.join("/","S", "M", "L", "XL"); //all=”S/M/L/XL”
字符串大小写切换
大写转换 String.toUpperCase();
小写转换 String.toLowerCase();
将数字格式化为货币字符串
public final String format(double number){
Scanner scan=new Scanner(System.in);
System.out.println("请输入一个数字:");
double number=scan.nextDouble();
System.out.println("该数字用Local类的常量作为格式化对象的构造参数,将获得不同的货币格式:");
//获取货币格式对象
NumberFormat format=NumberFormat.getCurrencyInstance(Locale.CHINA);
System.out.println("Locale.CHINA: "+format.format(number));
format=NumberFormat.getCurrencyInstance(Locale.US);
System.out.println("Locale.US: "+format.format(number));
}
格式化输出
使用
Double x=3333.33333333
System.out.printf(“%8.2f”,x); // 3333.33
用8个字符的宽度和小数点后两个字符的精度来打印x,即输出一个空格和7个字符
printf语法图
用于printf的转换符
printf的标志
类型转换
Integer转换2、8、16进制转换
二进制:Integer.toBinaryString();
八进制:Integer.toOctalString();
十六进制:Integer.toHexString();
网络传输
获取Ip地址
public class IpAdrressUtil {
/**
* 获取Ip地址
* @param request
* @return
*/
private static String getIpAdrress(HttpServletRequest request) {
String Xip = request.getHeader("X-Real-IP");
String XFor = request.getHeader("X-Forwarded-For");
if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = XFor.indexOf(",");
if(index != -1){
return XFor.substring(0,index);
}else{
return XFor;
}
}
XFor = Xip;
if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
return XFor;
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getRemoteAddr();
}
return XFor;
}
}
使用httpclient实现后台java发送post和get请求
doGET()
public static String doGet() {
String result = null;
//请求地址
String url = "";
//获取请求参数
List<NameValuePair> parame = new ArrayList<NameValuePair>();
parame.add(new BasicNameValuePair("参数名", 参数值);
// 获取httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String parameStr = null;
try {
parameStr = EntityUtils.toString(new UrlEncodedFormEntity(parame));
//拼接参数
StringBuffer sb = new StringBuffer();
sb.append(url);
sb.append("?");
sb.append(parameStr);
//创建get请求
HttpGet httpGet = new HttpGet(sb.toString());
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000).setConnectTimeout(2000).build();
httpGet.setConfig(requestConfig);
// 提交参数发送请求
response = httpclient.execute(httpGet);
// 得到响应信息
int statusCode = response.getStatusLine().getStatusCode();
// 判断响应信息是否正确
if (statusCode != HttpStatus.SC_OK) {
// 终止并抛出异常
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
EntityUtils.consume(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭所有资源连接
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpclient != null) {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result.toString();
}
doPost()
public static String doPost(){
String result = null;
//请求地址
String url = "";
List<NameValuePair> parameForToken = new ArrayList<NameValuePair>();
parameForToken.add("参数名", 参数值);
// 获取httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
//创建post请求
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000).setConnectTimeout(2000).build();
httpPost.setConfig(requestConfig);
// 提交参数发送请求
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parame);
httpPost.setEntity(urlEncodedFormEntity);
response = httpclient.execute(httpPost);
// 得到响应信息
int statusCode = response.getStatusLine().getStatusCode();
// 判断响应信息是否正确
if (statusCode != HttpStatus.SC_OK) {
// 终止并抛出异常
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
//result = EntityUtils.toString(entity);//不进行编码设置
result = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭所有资源连接
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpclient != null) {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/117540.html