文章目錄
- 産生随機數
- 擷取目前時間、日期,上一周、下一周等
- 基本資料類型如何比較是否相等、引用類型如何比較是否相等
- 重定向輸出流實作程式日志
- Scanner
-
- 從控制台接受輸入字元
- 數組
-
- 數組拷貝Arrays.copyOf()
- 反轉數組
- 循環
-
- for、while循環、switch中斷控制流程語句
- 退出雙層for循環
- 字元串
-
- 拼接字元串
- 字元串大小寫切換
- 将數字格式化為貨币字元串
- 格式化輸出
- 類型轉換
-
- Integer轉換2、8、16進制轉換
- 網絡傳輸
-
- 擷取Ip位址
- 使用httpclient實作背景java發送post和get請求
産生随機數
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類的标準輸入流
2.效果
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;
}