·····X0·····
·····X1·····
目录
- one hundred string manipulation(字符串操作)
- one hundred and one array manipulation(数组操作)
- one hundred and two time manipulation(时间操作)
- one hundred and three Of All the Ways (方法)
- one hundred and four Print various graphics (图形)
- one hundred and five file operations(文件操作)
- one hundred and six Directory operation(目录操作)
- one hundred and seven exception handling(异常处理)
- one hundred and eight data structure(数据结构)
- one hundred and nine set(集合)
- one hundred and ten Java Network instance(网络实例)
- one hundred and eleven thread(线程)
- one hundred and twelve Java Environment setting instance(环境设置)
- one hundred and thirteen log(日志)
- one hundred and fourteen timed task(timer)(定时器)
- one hundred and fifteen export(导出)
- one hundred and sixteen network gateway(网络网关)
- one hundred and seventeen Java ehcache(cache)(缓存)
- one hundred and eighteen Linux,Windows,MacOS System judgment(操作系统)
- one hundred and nineteen DB
- one hundred and twenty sql
- one hundred and twenty-one Entity class attribute sorting(实体类属性排序)
- one hundred and twenty-two Hexadecimal to a character string(十六进制字符串)
- one hundred and twenty-three Hexadecimal to a character string(idea编码,快捷键...)
- SocketClient(持续连接)
one hundred string manipulation(字符串操作)
比较
public static void main(String[] args) {
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;
System.out.println( str.compareTo(anotherString) );
System.out.println( str.compareToIgnoreCase(anotherString) ); //忽略大小写
System.out.println( str.compareTo(objStr.toString()));
}
最后一次出现的位置
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Runoob";
int lastIndex = strOrig.lastIndexOf("Runoob");
if(lastIndex == - 1){
System.out.println("没有找到字符串 Runoob");
}else{
System.out.println("Runoob 字符串最后出现的位置: "+ lastIndex);
}
}
替换
public static void main(String args[]){
String str="Hello World";
System.out.println( str.replace( 'H','W' ) );
System.out.println( str.replaceFirst("He", "Wa") );
System.out.println( str.replaceAll("He", "Ha") );
}
反转
public static void main(String[] args){
String string="runoob";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("字符串反转前:"+string);
System.out.println("字符串反转后:"+reverse);
}
查找
public static void main(String[] args) {
String strOrig = "Google Runoob Taobao";
int intIndex = strOrig.indexOf("Runoob");
if(intIndex == - 1){
System.out.println("没有找到字符串 Runoob");
}else{
System.out.println("Runoob 字符串位置 " + intIndex);
}
}
分割
public static void main(String args[]){
String str = "www-runoob-com";
String[] temp;
String delimeter = "-"; // 指定分割字符
temp = str.split(delimeter); // 分割字符串
// 普通 for 循环
for(int i =0; i < temp.length ; i++){
System.out.println(temp[i]);
System.out.println("");
}
System.out.println("------java for each循环输出的方法-----");
String str1 = "www.runoob.com";
String[] temp1;
String delimeter1 = "\\."; // 指定分割字符, . 号需要转义
temp1 = str1.split(delimeter1); // 分割字符串
for(String x : temp1){
System.out.println(x);
System.out.println("");
}
}
分割StringTokenizer方法
public static void main(String[] args) {
String str = "This is String , split by StringTokenizer, created by runoob";
StringTokenizer st = new StringTokenizer(str);
System.out.println("----- 通过空格分隔 ------");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
System.out.println("----- 通过逗号分隔 ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
}
小写转大写
public static void main(String[] args) {
String str = "string runoob";
String strUpper = str.toUpperCase();
System.out.println("原始字符串: " + str);
System.out.println("转换为大写: " + strUpper);
}
两个字符串区域是否相等
public static void main(String[] args){
String first_str = "Welcome to Microsoft";
String second_str = "I work with microsoft";
boolean match1 = first_str.
regionMatches(11, second_str, 12, 9);
boolean match2 = first_str.
regionMatches(true, 11, second_str, 12, 9); //第一个参数 true 表示忽略大小写区别
System.out.println("区分大小写返回值:" + match1);
System.out.println("不区分大小写返回值:" + match2);
}
性能比较
public static void main(String[] args){
long startTime = System.currentTimeMillis();
for(int i=0;i<50000;i++){
String s1 = "hello";
String s2 = "hello";
}
long endTime = System.currentTimeMillis();
System.out.println("通过 String 关键词创建字符串"
+ " : "+ (endTime - startTime)
+ " 毫秒" );
long startTime1 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
String s3 = new String("hello");
String s4 = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("通过 String 对象创建字符串"
+ " : " + (endTime1 - startTime1)
+ " 毫秒");
}
优化
public static void main(String[] args){
String variables[] = new String[50000];
for( int i=0;i <50000;i++){
variables[i] = "s"+i;
}
long startTime0 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
variables[i] = "hello";
}
long endTime0 = System.currentTimeMillis();
System.out.println("直接使用字符串: "+ (endTime0 - startTime0) + " ms" );
long startTime1 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
variables[i] = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("使用 new 关键字:" + (endTime1 - startTime1) + " ms");
long startTime2 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
variables[i] = new String("hello");
variables[i] = variables[i].intern();
}
long endTime2 = System.currentTimeMillis();
System.out.println("使用字符串对象的 intern() 方法: "
+ (endTime2 - startTime2)
+ " ms");
}
格式化
public static void main(String[] args){
double e = Math.E;
System.out.format("%f%n", e);
System.out.format(Locale.CHINA , "%-10.4f%n%n", e); //指定本地为中国(CHINA)
}
连接字符串
public static void main(String[] args){
long startTime = System.currentTimeMillis();
for(int i=0;i<5000;i++){
String result = "This is"
+ "testing the"
+ "difference"+ "between"
+ "String"+ "and"+ "StringBuffer";
}
long endTime = System.currentTimeMillis();
System.out.println("字符串连接"
+ " - 使用 + 操作符 : "
+ (endTime - startTime)+ " ms");
long startTime1 = System.currentTimeMillis();
for(int i=0;i<5000;i++){
StringBuffer result = new StringBuffer();
result.append("This is");
result.append("testing the");
result.append("difference");
result.append("between");
result.append("String");
result.append("and");
result.append("StringBuffer");
}
long endTime1 = System.currentTimeMillis();
System.out.println("字符串连接"
+ " - 使用 StringBuffer : "
+ (endTime1 - startTime1)+ " ms");
}
·····X0·····
判断为空
String.equals("")
String==null
String.isEmpty()
StringUtils.isBlank(String)
分裂
String s="114-14 234-25 235+1425 334+1114 225+14567 125-17 12";
String[] s1 = s.split(" ");
for (int i = 0; i<s1.length;i++){
System.out.println(s1[i]);
}
截取连续字符串(1和2之间所有) 00100200100200100200
/*
*开始与结束位置不相同 0010020010200 →→→ 开始1,结束2 →→→获取00,0
*data 原始数据
*begin 开始位置
*over 结束位置
*return 多次获取,开始与结束之间的值
*/
public static String value(String data,String begin,String over){
int count = 0;
//记录找到的索引
int i = 0;
String sstring = "";
while (true) {
if (data.indexOf(begin, i) == -1) {
break; //找不到,跳出来
} else {
count++; //找到,计数
i = data.indexOf(begin, i) + 1; //更新查找索引值,继续找
}
}
for (int q = 0; q < count ; q++) {
sstring = gain(data,begin,over) + "," + sstring;
data = out(data,begin,over);
}
int i1 = sstring.lastIndexOf(",");
String substring = "";
if (i1 + 1 == sstring.length()) {
substring = sstring.substring(0, i1);
}
System.out.println("substring===>\n" + substring);
return substring;
}
public static String gain(String data,String begin,String over) {
data = data.replaceAll(" ", "");
data = data.replaceAll("\n", "");
data = data.replaceAll(" ", "");
String error = data.substring(data.indexOf(begin) + begin.length(), data.indexOf(over));
return error;
}
public static String out(String data,String begin,String over) {
data = data.replaceAll(" ", "");
data = data.replaceAll("\n", "");
data = data.replaceAll(" ", "");
data = data.substring(0, data.indexOf(begin)) + data.substring(data.indexOf(over) + over.length());
return data;
}
, 之间用null 填充 (逗号之间为空,用null)
class test7 {
public static void main(String[] args) {
String cc = "1,False,48,タ盽у,GAAP3107,T2E て簧\uE09E疢疦_006._CH1,,SB_Idle,7,GAAP,,琿计,34,,1,,1.00,1,,=,,GAAP,,材1琿_ヘ夹放\uE094,10,115,110,105,1.00,110,<=,,>=,GAPP,,材1琿_\uE0AA放\uE1A0丁,16,45,40,35,1.00,40,<=,,>=,GAPP,,\uE129放\uE1A0丁,31,,3,,1.00,3,,=,,GAPP,,箇荐\uE5FD\uE126,32,,1,,1.00,0,,=,,GAPP,,箇荐\uE5FB\uE126,33,,1,,1.00,0,,=,,GAPP,,材1琿_ど放\uE1A0丁,25,,5,,1.00,5,,=,\n";
String[] a = cc.split(","); //切割
ArrayList list =new ArrayList();
for (int i=0;i<a.length;i++){
if (a[i].isEmpty()){ //为空
a[i]="null";
}
list.add(a[i]); //组合
System.out.println(a[i]);
}
System.out.println(list);
}
}
字符串出现的次数
class test5 {
public static void main(String[] args) {
String str = "www.baidu.com/www.sina.com/www.baidu.com/www.sina.com";
String subStr = "w";
System.out.println(str(str, subStr));
}
public static int str(String data,String subStr){
int count = 0;
int i = 0;
while (true) {
if (data.indexOf(subStr, i) == -1) {
break;
} else {
count++;
i = data.indexOf(subStr, i) + 1;
}
}
return count;
}
}
查询字符串 第n次 所在的下标
class test3 {
public static void main(String[] args) {
//前置数据 9个,7组,每组12
String s = "1,False,48,タ盽у,GAAP3107,T2E て簧\uE09E疢疦_006._CH1,,SB_Idle,7,GAAP,,琿计,34,,1,,1.00,1,,=,,GAAP,,材1琿_ヘ夹放\uE094,10,115,110,105,1.00,110,<=,,>=,GAPP,,材1琿_\uE0AA放\uE1A0丁,16,45,40,35,1.00,40,<=,,>=,GAPP,,\uE129放\uE1A0丁,31,,3,,1.00,3,,=,,GAPP,,箇荐\uE5FD\uE126,32,,1,,1.00,0,,=,,GAPP,,箇荐\uE5FB\uE126,33,,1,,1.00,0,,=,,GAPP,,材1琿_ど放\uE1A0丁,25,,5,,1.00,5,,=,";
System.out.println(s);
int index = getIndex(s, 8, ",");
int index1 = getIndex(s, 9, ",");
System.out.println(index+"\n"+index1);
System.out.println(s.substring(index+1,index1));
}
/**
string:原始数据字符串
i:出现的次数
str:需要查询的字符串
return:具体的下标
* */
public static int getIndex(String string, int i, String str) {
Matcher slashMatcher = Pattern.compile(str).matcher(string);
int mIdx = 0;
while (slashMatcher.find()) {
mIdx++;
if (mIdx == i) {
break;
}
}
return slashMatcher.start();
}
}
public class test1 {
@Test
public void test4() {
String x = "1324576884";
System.out.println(x.substring(2,5)); //245 (截取字符串下标2之5之间)
System.out.println(x.charAt(4)); //245 (下标为4的字符串)
String s = "http://127.0.0.1:8000/";
if (s.endsWith("/")) {
contextUrl = contextUrl.substring(0, contextUrl.length() - 1);
}
}
}
@Test
public void test4() {
String x = "13245777778485612349999964866"; //除去中间只留两边 去除a和b之间 //1324564866
String a = "77777";
String b = "99999";
int i1 = x.indexOf(a);
int i2 = x.indexOf(b);
String s1 = x.substring(0, 5); //截取0-5 //13245
String s2 = x.substring(19); //截取19到结束 //9999964866
String s3 = x.substring(19 + b.length()); //64866
System.out.println(
"下标5==> \n"+i1
+"\n 下标19==> \n"+i2
+"\n 截取0-5==> \n"+s1
+"\n 截取19到结束==> \n"+s2
+"\n 截取(19+自身长度)到结束==> \n"+s3
+"\n 去除a,b 之间 + a,b自身===> \n"+(s1+s3)
);
}
class test4 {
public static void main(String[] args) {
String str = "123asd123asd123asd";
str.indexOf("a"); // 从头开始查找str在字符串中第一次出现的位置;
str.indexOf("a",4); // 起始位置下标4,开始查找str在字符串中第一次出现的位置;
str.lastIndexOf("a"); // 从尾部开始查找str在字符串中最后一次出现的位置;
str.lastIndexOf("a",2); // 从起始位置下标1,开始开始查找str在字符串中最后一次出现的位置;
System.out.println(str.indexOf("a")+"\n"+str.indexOf("a",4)+"\n"+str.lastIndexOf("a")+"\n"+str.lastIndexOf("a",2)+"\n"+"-1代表没有,重定义初始位置(fromIndex)。");
}
}
class test4 {
public static void main(String[] args) {
46352823171413108865
40352820171411108765
46402523171213117874
46 40 35 28 25 23 20 17 14 13 12 11 10 8 7 6 5 4
String s = " 46 35 28 23 17 14 13 10 8 8 6 5 244\n" +
" 4 6 8 10 14 16 18 22 30 30 40 46 244\n" +
" 40 35 28 20 17 14 11 10 8 7 6 5 248\n" +
" 6 6 8 10 12 16 20 22 30 32 40 46 248\n" +
" 46 40 25 23 17 12 13 11 7 8 7 4 251\n" +
" 4 6 8 10 14 17 18 20 32 30 32 60 251\n" +
"";
数(1): 46×5105100 = 最小公倍数234834600 ,46÷46 = 最大公约数1
数(2): 40×5870865 = 最小公倍数234834600 ,40÷40 = 最大公约数1
数(3): 35×6709560 = 最小公倍数234834600 ,35÷35 = 最大公约数1
数(4): 28×8386950 = 最小公倍数234834600 ,28÷28 = 最大公约数1
数(5): 25×9393384 = 最小公倍数234834600 ,25÷25 = 最大公约数1
数(6): 23×10210200 = 最小公倍数234834600 ,23÷23 = 最大公约数1
数(7): 20×11741730 = 最小公倍数234834600 ,20÷20 = 最大公约数1
数(8): 17×13813800 = 最小公倍数234834600 ,17÷17 = 最大公约数1
数(9): 14×16773900 = 最小公倍数234834600 ,14÷14 = 最大公约数1
数(10): 13×18064200 = 最小公倍数234834600 ,13÷13 = 最大公约数1
数(11): 12×19569550 = 最小公倍数234834600 ,12÷12 = 最大公约数1
数(12): 11×21348600 = 最小公倍数234834600 ,11÷11 = 最大公约数1
数(13): 10×23483460 = 最小公倍数234834600 ,10÷10 = 最大公约数1
数(14): 8×29354325 = 最小公倍数234834600 ,8÷8 = 最大公约数1
数(15): 7×33547800 = 最小公倍数234834600 ,7÷7 = 最大公约数1
数(16): 6×39139100 = 最小公倍数234834600 ,6÷6 = 最大公约数1
数(17): 5×46966920 = 最小公倍数234834600 ,5÷5 = 最大公约数1
数(18): 4×58708650 = 最小公倍数234834600 ,4÷4 = 最大公约数1
String str1 = "123asd123asd123asd";
Pattern pattern = Pattern.compile("a"); //需要查询的具体字符串
int index=2; //第n次位置
int indexNum=0; //标记
Matcher findMatcher = pattern.matcher(str1);
while (findMatcher.find()) {
indexNum++;
if(indexNum==index){
break;
}
}
System.out.println("第"+index+"次出现的位置为:"+findMatcher.start());
}
}
查询字符串第n次出现的位置下表
class test4 {
public static void main(String[] args) {
String str1 = "123asd123asd123asd";
Pattern pattern = Pattern.compile("a"); //需要查询的具体字符串
int index=2; //第n次位置
int indexNum=0; //标记
Matcher findMatcher = pattern.matcher(str1);
while (findMatcher.find()) {
indexNum++;
if(indexNum==index){
break;
}
}
System.out.println("第"+index+"次出现的位置为:"+findMatcher.start());
}
}
二维数组int[][],String[][]
public static void main(String[] args) {
int[][] arr = { {0, 0, 0, 0}, {1, 1, 1, 1}, {2,2, 2, 2}, {3, 3, 3, 3} };
for(int i = 0; i < arr.length; i++) {
//遍历二维数组的每个元素(数组)。 1. arr[i] 表示 二维数组的第 i+1 个元素 比如 arr[0]:二维数组的第一个元素。 2. arr[i].length 得到 对应的 每个一维数组的长度
for(int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");//输出了一维数组
}
System.out.println();//换行
}
}
public static void main(String[] args) {
String[][] arr = { {"0", "0", "00", "0"}, {"1", "1", "01", "1"}, {"2","2", "02", "2"}, {"3", "3", "03", "3"} };
for(int i = 0; i < arr.length; i++) {
//遍历二维数组的每个元素(数组)。 1. arr[i] 表示 二维数组的第 i+1 个元素 比如 arr[0]:二维数组的第一个元素。 2. arr[i].length 得到 对应的 每个一维数组的长度
for(int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");//输出了一维数组
}
System.out.println();//换行
}
}
public static void main(String[] args) {
String[][] arr = new String[5][1]; //{{1},{2},{3},{4},{5}}
for(int i = 0; i < arr.length; i++) {
//遍历二维数组的每个元素(数组)。 1. arr[i] 表示 二维数组的第 i+1 个元素 比如 arr[0]:二维数组的第一个元素。 2. arr[i].length 得到 对应的 每个一维数组的长度
for(int j = 0; j < arr[i].length; j++) {
int x = i;
arr[i][j]= "赋值:" +x;
System.out.print(arr[i][j] + " ");//输出了一维数组
}
System.out.println();//换行
}
}
public static void main(String[] args) {
String[][] tableValueList = new String[3][1];//长度三行,一列
tableValueList[0][0]="00001";//一行,一列 下标 零 零
tableValueList[1][0]="00002";//二行,一列 下标 一 零
tableValueList[2][0]="00003";//三行,一列 下标 二 零
}
//chinaunix,itpub,51cto,落伍者,蓝色理想,it写作社区,博客堂,it英雄榜,邪恶八进制,
Stack Overflow,Reddit,Google+ Communities,SitePoint,CodeProject,Treehouse,Hacker News,
DZone,Bytes,DaniWeb,Dream In Code,Tech.Pro,Pineapple,Lobsters,学优IT
public static void main(String[] args) {
String s1 = "<data>\n" +
"<machine>\n" +
"<info>1</info>\n" +
"<error>83</error>\n" +
"<error>29</error>\n" +
"<error>230 2 3 4 5</error>\n" +
"</machine>\n" +
"</data>";
//得到
//83
//29
//230 2 3 4 5
//或
//83
//29
//230
String s2 = s1.split("<machine>")[1].split("</machine>")[0];
System.out.println(s2);
for (int i = 0; i < s2.split("<error>").length; i++) {
if (s2.split("<error>")[i].contains("</error>")) {
String key = s2.split("<error>")[i].split("</error>")[0];
// System.out.println(key);
if (key.contains(" ")) {
key = key.substring(0, key.indexOf(" "));
}
System.out.println(key);
}
}
}
文件
mesAgentConfig/jobGram.pro
内容
AH1=H-2.4
AH2=H-6.8
AH3=H-CEM-3-ZY
AH4=H-D22-ZY
AH5=H-D50-ZY
AH6=H-DR-1.6mm-3
AH7=H-DR-1.6mm-3-HF
AH8=H-DR-2-HF
AH9=H-DR-10.12
AH10=H-HF
得到 值 (或通过key得到value)
H-2.4
H-6.8
H-CEM-3-ZY
H-D22-ZY
H-D50-ZY
H-DR-1.6mm-3
H-DR-1.6mm-3-HF
H-DR-2-HF
H-DR-10.12
H-HF
public class JobGram {
ClsPropertySet jobGram = new ClsPropertySet(System.getProperty("user.dir") + File.separator + "mesAgentConfig" + File.separator + "jobGram.pro");
String AH1 = jobGram.getPropertyStr("AH1", ""); //获取属性值
public static void main(String[] args) {
JobGram jobGram = new JobGram();
jobGram.str();
}
public void str(){
try {
Path path = Paths.get(System.getProperty("user.dir") + File.separator + "mesAgentConfig" + File.separator + "jobGram.pro");
byte[] data = java.nio.file.Files.readAllBytes(path);
String s2 = new String(data, "utf-8");
for (int i = 0; i < s2.split("=").length; i++) {
if (s2.split("=")[i].contains("\n")) {
String key = s2.split("=")[i].split("\n")[0];
System.out.println(key);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public class ClsPropertySet {
protected Properties properties;
private String propertyFileName;
public ClsPropertySet() {
properties = new Properties();
}
/**
* Constructor with configuration file
*/
public ClsPropertySet(String flName) {
properties = new Properties();
loadPropertiesFrom(flName);
propertyFileName = flName;
}
public Properties getProperties() {
return properties;
}
/**
* set the file name
*/
public void setFileName(String flName) {
propertyFileName = flName;
}
/**
* Read property values ??from a file
*/
public boolean loadPropertiesFrom(String flName) {
return loadProperties(flName);
}
/**
* Save configuration values ??in the current file
*/
public boolean saveProperties() {
return saveProperties(propertyFileName);
}
/**
* Save configuration values ??to a new file
*/
public boolean savePropertiesTo(String flName) {
return saveProperties(flName);
}
public boolean savePropertiesTo(String path, String flName) {
return saveProperties(path + flName);
}
/**
* return the current path name
*/
public String getPropertyFileName() {
return propertyFileName;
}
/** read access to the configuration data */
/** ======================================================================== */
/**
* Load configuration value as a string
*/
public String getPropertyStr(String key, String def) {
if (def != null) {
return properties.getProperty(key, def);
} else {
return properties.getProperty(key);
}
}
/**
* Load configuration value as Boolean
*/
public Boolean getPropertyBool(String key, Boolean def) {
String str;
if (def != null) {
str = properties.getProperty(key, def.toString());
} else {
str = properties.getProperty(key);
}
return Boolean.valueOf(str);
}
/**
* Load configuration value as an integer
*/
public Integer getPropertyInt(String key, Integer def) {
String str;
if (def != null) {
str = properties.getProperty(key, def.toString());
} else {
str = properties.getProperty(key);
}
if (str == null) {
return null;
} else {
try {
return Integer.valueOf(str.trim());
} catch (NumberFormatException nfe) {
System.out.println(new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss.SSS").format(new Date().getTime()) + " " + nfe);
return null;
}
}
}
/**
* Load configuration value as long
*/
public Long getPropertyLong(String key, Long def) {
String str;
if (def != null) {
str = properties.getProperty(key, def.toString());
} else {
str = properties.getProperty(key);
}
if (str == null) {
return null;
} else {
try {
return new Long(str);
} catch (NumberFormatException nfe) {
return null;
}
}
}
/**
* Load configuration value as float
*/
public Float getPropertyFloat(String key, Float def) {
String str;
if (def != null) {
str = properties.getProperty(key, def.toString());
} else {
str = properties.getProperty(key);
}
if (str == null) {
return null;
} else {
try {
return Float.valueOf(str);
} catch (NumberFormatException nfe) {
return null;
}
}
}
/** write access to the configuration data */
/** ======================================================================== */
/**
* save string as configuration value
*/
public boolean setPropertyStr(String key, String val) {
return properties.setProperty(key, val) != null;
}
/**
* Save Boolean as configuration value
*/
public boolean setPropertyBool(String key, boolean val) {
String bool;
if (val) {
bool = "true";
} else {
bool = "false";
}
return properties.setProperty(key, bool) != null;
}
/**
* Save integer as configuration value
*/
public boolean setPropertyInt(String key, int val) {
return properties.setProperty(key, Integer.toString(val)) != null;
}
/**
* save float as configuration value
*/
public boolean setPropertyFloat(String key, float val) {
return properties.setProperty(key, Float.toString(val)) != null;
}
/** auxiliary methods */
/** ======================================================================== */
/**
* Read property values ??from a file
*/
protected boolean loadProperties(String flName) {
FileInputStream sf = null;
try {
if (flName == null) {
flName = propertyFileName;
}
sf = new FileInputStream(flName);
properties.load(sf);
propertyFileName = flName;
sf.close();
return true;
} catch (IOException ie) {
System.err.println(new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss.SSS").format(new Date().getTime()) + " " + "Can't load config file: " + flName + " (" + ie + ")");
try {
if (sf != null) {
sf.close();
}
} catch (IOException ioe) {
}
;
return false;
}
}
/** auxiliary methods */
/** ======================================================================== */
/**
* Read property values ??from a file
*/
protected boolean loadPropertiesStream(String flName) {
InputStream sf = null;
try {
if (flName == null) {
flName = propertyFileName;
}
sf = new FileInputStream(flName);
// sf = MainFrame.class.getClassLoader().getResourceAsStream(flName);
properties.load(sf);
propertyFileName = flName;
sf.close();
return true;
} catch (IOException ie) {
System.err.println(new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss.SSS").format(new Date().getTime()) + " " + "can't load config file: " + flName + " (" + ie + ")");
try {
if (sf != null) {
sf.close();
}
} catch (IOException ioe) {
}
;
return false;
}
}
/**
* Save configuration values in a new file
*/
protected boolean saveProperties(String flName) {
FileOutputStream sf = null;
try {
sf = new FileOutputStream(flName);
properties.store(sf, null);
sf.close();
return true;
} catch (IOException ie) {
System.err.println(new SimpleDateFormat("dd/MM/yyyy, HH:mm:ss.SSS").format(new Date().getTime()) + " " + "can't save config file: " + flName + " (" + ie + ")");
try {
if (sf != null) {
sf.close();
}
} catch (IOException ioe) {
}
;
if (sf != null) {
try {
sf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}
}
·····X1·····
···················································································································································································
one hundred and one array manipulation(数组操作)
排序及元素查找
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("数组排序结果为", array);
int index = Arrays.binarySearch(array, 2);
System.out.println("元素 2 在第 " + index + " 个位置");
}
private static void printArray(String message, int array[]) {
System.out.println(message
+ ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if(i != 0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
添加元素
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("数组排序", array);
int index = Arrays.binarySearch(array, 1);
System.out.println("元素 1 所在位置(负数为不存在):"
+ index);
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("数组添加元素 1", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message
+ ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if (i != 0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[],
int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index
+ 1, length - index);
return destination;
}
长度
public static void main(String args[]) {
String[][] data = new String[2][5];
System.out.println("第一维数组长度: " + data.length);
System.out.println("第二维数组长度: " + data[0].length);
}
反转
static void reverse(int a[], int n)
{
int[] b = new int[n];
int j = n;
for (int i = 0; i < n; i++) {
b[j - 1] = a[i];
j = j - 1;
}
/*输入反转数组*/
System.out.println("反转后数组是: \n");
for (int k = 0; k < n; k++) {
System.out.println(b[k]);
}
}
public static void main(String[] args)
{
int [] arr = {10, 20, 30, 40, 50};
reverse(arr, arr.length);
}
输出
public static void main(String[] args){
String[] runoobs = new String[3];
runoobs[0] = "菜鸟教程";
runoobs[1] = "菜鸟工具";
runoobs[2] = "菜鸟笔记";
for (int i = 0; i < runoobs.length; i++){
System.out.println(runoobs[i]);
}
}
最大值,最小值
public static void main(String[] args) {
Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
int min = (int) Collections.min(Arrays.asList(numbers));
int max = (int) Collections.max(Arrays.asList(numbers));
System.out.println("最小值: " + min);
System.out.println("最大值: " + max);
}
·····X0·····
public static void main(String[] args) {
int[] a =new int[]{1,5,8,2,3,9,4};
int max = getMax(a);
System.out.println(max);
}
public static int getMax(int[] arr){
int max=arr[0];
for (int x=1;x<arr.length;x++){
if(arr[x]>max){
max=arr[x];
}
}
return max;
}
·····X1·····
合并
public static void main(String args[]) {
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));
}
填充
public static void main(String args[]) {
int array[] = new int[6];
Arrays.fill(array, 100);
for (int i=0, n=array.length; i < n; i++) {
System.out.println(array[i]);
}
System.out.println();
Arrays.fill(array, 3, 6, 50);
for (int i=0, n=array.length; i< n; i++) {
System.out.println(array[i]);
}
}
扩容
public static void main(String[] args) {
String[] names = new String[] { "A", "B", "C" };
String[] extended = new String[5];
extended[3] = "D";
extended[4] = "E";
System.arraycopy(names, 0, extended, 0, names.length);
for (String str : extended){
System.out.println(str);
}
}
查找数组中的重复元素
public static void main(String[] args)
{
int[] my_array = {1, 2, 5, 5, 6, 6, 7, 2, 9, 2};
findDupicateInArray(my_array);
}
public static void findDupicateInArray(int[] a) {
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k]) {
count++;
}
}
if(count==1)
System.out.println( "重复元素 : " + a[j] );
count = 0;
}
}
删除
public static void main(String[] args) {
int[] oldarray = new int[] {3, 4, 5, 6, 7};// 原始数组
int num = 2; // 删除索引为 2 的元素,即删除第三个元素 5
int[] newArray = new int[oldarray.length-1];// 新数组,长度为原始数组减去 1
for(int i=0;i<newArray.length; i++) {
// 判断元素是否越界
if (num < 0 || num >= oldarray.length) {
throw new RuntimeException("元素越界... ");
}
//
if(i<num) {
newArray[i] = oldarray[i];
}
else {
newArray[i] = oldarray[i+1];
}
}
// 打印输出数组内容
System.out.println(Arrays.toString(oldarray));
oldarray = newArray;
System.out.println(Arrays.toString(oldarray));
}
差集
public static void main(String[] args) {
ArrayList objArray = new ArrayList();
ArrayList objArray2 = new ArrayList();
objArray2.add(0,"common1");
objArray2.add(1,"common2");
objArray2.add(2,"notcommon");
objArray2.add(3,"notcommon1");
objArray.add(0,"common1");
objArray.add(1,"common2");
objArray.add(2,"notcommon2");
System.out.println("array1 的元素" +objArray);
System.out.println("array2 的元素" +objArray2);
objArray.removeAll(objArray2);
System.out.println("array1 与 array2 数组差集为:"+objArray);
}
交集
public static void main(String[] args) {
ArrayList objArray = new ArrayList();
ArrayList objArray2 = new ArrayList();
objArray2.add(0,"common1");
objArray2.add(1,"common2");
objArray2.add(2,"notcommon");
objArray2.add(3,"notcommon1");
objArray.add(0,"common1");
objArray.add(1,"common2");
objArray.add(2,"notcommon2");
System.out.println("array1 数组元素:"+objArray);
System.out.println("array2 数组元素:"+objArray2);
objArray.retainAll(objArray2);
System.out.println("array2 & array1 数组交集为:"+objArray);
}
找指定元素
public static void main(String[] args) {
ArrayList<String> objArray = new ArrayList<String>();
ArrayList<String> objArray2 = new ArrayList<String>();
objArray2.add(0,"common1");
objArray2.add(1,"common2");
objArray2.add(2,"notcommon");
objArray2.add(3,"notcommon1");
objArray.add(0,"common1");
objArray.add(1,"common2");
System.out.println("objArray 的数组元素:"+objArray);
System.out.println("objArray2 的数组元素:"+objArray2);
System.out.println("objArray 是否包含字符串common2? : "
+objArray.contains("common2"));
System.out.println("objArray2 是否包含数组 objArray? :"
+objArray2.contains(objArray) );
}
是否相等
public static void main(String[] args) throws Exception {
int[] ary = {1,2,3,4,5,6};
int[] ary1 = {1,2,3,4,5,6};
int[] ary2 = {1,2,3,4};
System.out.println("数组 ary 是否与数组 ary1相等? :"
+Arrays.equals(ary, ary1));
System.out.println("数组 ary 是否与数组 ary2相等? :"
+Arrays.equals(ary, ary2));
}
并集
public static void main(String[] args) throws Exception {
String[] arr1 = { "1", "2", "3" };
String[] arr2 = { "4", "5", "6" };
String[] result_union = union(arr1, arr2);
System.out.println("并集的结果如下:");
for (String str : result_union) {
System.out.println(str);
}
}
// 求两个字符串数组的并集,利用set的元素唯一性
public static String[] union(String[] arr1, String[] arr2) {
Set<String> set = new HashSet<String>();
for (String str : arr1) {
set.add(str);
}
for (String str : arr2) {
set.add(str);
}
String[] result = { };
return set.toArray(result);
}
·····X0·····
冒泡
public static void main(String[] args) {
//排序
int[] a =new int[]{1,5,8,2,3,9,4};
//需进行length-1次冒泡
for(int i=0;i<a.length-1;i++) {
for(int j=0;j<a.length-1-i;j++) {
if(a[j]>a[j+1]) {
int b =a[j];
a[j]=a[j+1];
a[j+1]= b ;
}
}
}
System.out.println("从小到大排序后的结果是:");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
}
//(String字符串) 或(String类型数组)反转
class test22{
public static void main(String[] args) {
// 字符串转数组
String str = "02,13,25,37,4,5";
String[] strArray = str.split(","); // 用,分割 成数组
strArray(strArray);
}
public static void strArray(String[] strArray){
//数组反转
for (int i = 0; i < strArray.length/2; i++) {
String temp = strArray[i];
strArray[i] = strArray[strArray.length-i-1];
strArray[strArray.length-i-1] = temp;
}
//打印反转后数组
System.out.println("strArray反转后");
for (int i = 0; i < strArray.length; i++) {
System.out.print(strArray[i]+",");
}
}
}
String类型数组转int类型数组,int类型数组反转
//String类型数组转int类型数组(逗号隔开的String类型数组 ; 如果空格隔开,则把逗号换成空格)
public static int[] strArr(String s){
String[] strArr = s.split(",");
//创建一个int类型的数组.
int [] numberArr = new int[strArr.length];
//把strArr中的数据进行类型转换并存入到int数组中
for (int i = 0; i < strArr.length; i++) {
int number = Integer.parseInt(strArr[i]);
numberArr[i] = number;
}
//遍历int类型的数组
System.out.println("int类型的数组为===>");
for (int i = 0; i < numberArr.length; i++) {
System.out.println(numberArr[i]);
}
return numberArr;
}
//int类型数组反转 ; 可用逗号隔开
static void reverse(int a[], int n) {
int[] b = new int[n];
int j = n;
for (int i = 0; i < n; i++) {
b[j - 1] = a[i];
j = j - 1;
}
/*输入反转数组*/
System.out.println("反转后数组是===> \n");
for (int k = 0; k < n; k++) {
// System.out.println(b[k]+",");//可用逗号隔开
System.out.println(b[k]);
}
}
反转
public class t7 {
static void reverse(int a[], int n) {
int[] b = new int[n];
int j = n;
for (int i = 0; i < n; i++) {
b[j - 1] = a[i];
j = j - 1;
}
/*输入反转数组*/
System.out.println("反转后数组是: \n");
for (int k = 0; k < n; k++) {
System.out.println(b[k]);
}
}
public static void main(String[] args)
{
int [] arr = {10, 20, 30, 40, 50};
reverse(arr, arr.length);
}
}
二维数组int[][],String[][]
public static void main(String[] args) {
int[][] arr = { {0, 0, 0, 0}, {1, 1, 1, 1}, {2,2, 2, 2}, {3, 3, 3, 3} };
for(int i = 0; i < arr.length; i++) {
//遍历二维数组的每个元素(数组)。 1. arr[i] 表示 二维数组的第 i+1 个元素 比如 arr[0]:二维数组的第一个元素。 2. arr[i].length 得到 对应的 每个一维数组的长度
for(int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");//输出了一维数组
}
System.out.println();//换行
}
}
public static void main(String[] args) {
String[][] arr = { {"0", "0", "00", "0"}, {"1", "1", "01", "1"}, {"2","2", "02", "2"}, {"3", "3", "03", "3"} };
for(int i = 0; i < arr.length; i++) {
//遍历二维数组的每个元素(数组)。 1. arr[i] 表示 二维数组的第 i+1 个元素 比如 arr[0]:二维数组的第一个元素。 2. arr[i].length 得到 对应的 每个一维数组的长度
for(int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");//输出了一维数组
}
System.out.println();//换行
}
}
public static void main(String[] args) {
String[][] arr = new String[5][1]; //{{1},{2},{3},{4},{5}}
for(int i = 0; i < arr.length; i++) {
//遍历二维数组的每个元素(数组)。 1. arr[i] 表示 二维数组的第 i+1 个元素 比如 arr[0]:二维数组的第一个元素。 2. arr[i].length 得到 对应的 每个一维数组的长度
for(int j = 0; j < arr[i].length; j++) {
int x = i;
arr[i][j]= "赋值:" +x;
System.out.print(arr[i][j] + " ");//输出了一维数组
}
System.out.println();//换行
}
}
class test81 {
public static void main(String[] args) throws Exception {
String str = "";
for (int i = 0; i<10;i++){
int[] ary = ary();
for (int j = 0; j<10;j++) {
System.out.print(ary[j] + " ");
if(ary[j]==1||ary[j]==3||ary[j]==5||ary[j]==7||ary[j]==9){
str= str + 1 ;
}else if(ary[j]==2||ary[j]==4||ary[j]==6||ary[j]==8||ary[j]==10){
str= str + 2 ;
}
}
System.out.println();
}
System.out.println(str);
}
public static int[] ary(){
int[] ary = new int[10]; // 数组
ArrayList temp = new ArrayList(); // 集合 ,临时集合temp存放1~10个数字
ArrayList list = new ArrayList(); //list集合存放需要的数字
for (int i = 1; i<11;i++){
temp.add(i);
}
int index = 0;
while (true) {
if (list.size() == 10) {
break;
}
int it = (int)temp.get((int) (Math.random() * 10));
if (list.contains(it)) {
continue;
} else {ary[index] = it;
list.add(it);
index++;
}
}
return ary;
}
}
简单存取数据
public static Map<String,Object> K_V = new HashMap<>();
K_V.put("dog","xiao hei");
Object dog = K_V.get("dog");
System.out.println("小狗的名字是:"+dog);
存数据,遍历数据,交集,合并,去重
public class JLerror {
public static Vector q = new Vector();
public static Vector w = new Vector();
public static void main(String[] args) {
String s1 = "<data>\n" +
"<machine>\n" +
"<info>1</info>\n" +
"<error>83</error>\n" +
"<error>29</error>\n" +
"<error>19</error>\n" +
"<error>230 2 3 4 5</error>\n" +
"</machine>\n" +
"</data>";
String s2 = "<data>\n" +
"<machine>\n" +
"<info>1</info>\n" +
"<error>83</error>\n" +
"<error>29</error>\n" +
"<error>39</error>\n" +
"<error>49</error>\n" +
"<error>230 2 3 4 5</error>\n" +
"</machine>\n" +
"</data>";
String s3 = "<data>\n" +
"<machine>\n" +
"<info>1</info>\n" +
"<error>100</error>\n" +
"<error>101</error>\n" +
"<error>102</error>\n" +
"</machine>\n" +
"</data>";
String s4 = "<data>\n" +
"<machine>\n" +
"<info>1</info>\n" +
"<error>19</error>\n" +
"<error>101</error>\n" +
"<error>102</error>\n" +
"</machine>\n" +
"</data>";
// error(s1);
// error(s2);
// error(s3);
System.out.println("1");
err(s1);
System.out.println("2");
err(s2);
System.out.println("3");
err(s3);
System.out.println("4");
err(s4);
}
public static void err(String str){
if(q.size()>0){
errorStr(str, w);
Vector contrast = contrast(q, w);
for (int i = 0; i < contrast.size(); i++){
q.remove(contrast.get(i));
w.remove(contrast.get(i));
}
Vector merge = merge(q, w);
q.clear();
w.clear();
for (int i = 0; i < merge.size(); i++){
q.add(merge.get(i));
}
for (int i = 0; i < q.size(); i++){
System.out.println("多次:"+q.get(i));
}
}else {
errorStr(str,q);
for (int i = 0; i < q.size(); i++){
System.out.println("第一次:"+q.get(i));
}
}
}
/**
* 将str 存入 v
*/
public static void errorStr (String str,Vector v){
String s2 = str.split("<machine>")[1].split("</machine>")[0];
for (int i = 0; i < s2.split("<error>").length; i++) {
if (s2.split("<error>")[i].contains("</error>")) {
String key = s2.split("<error>")[i].split("</error>")[0];
if (key.contains(" ")) {
key = key.substring(0, key.indexOf(" "));
}
v.add(key);
}
}
}
/**
* q 与 w 比较的差集 返回 a
*/
public static Vector contrast (Vector q,Vector w){
Vector a = new Vector();
for (int i = 0; i < q.size(); i++) {
Object o = q.get(i);
String s1 = o.toString();
for (int e = 0; e < w.size(); e++){
Object o1 = w.get(e);
String s2 = o1.toString();
if(s1.equals(s2)){
a.add(s1);
}
}
}
return a;
}
/**
* q 与 w 合并 返回 a
*/
public static Vector merge (Vector q,Vector w){
Vector a = new Vector();
for (int i = 0; i < q.size(); i++) {
a.add(q.get(i));
}
for (int i = 0; i < w.size(); i++) {
a.add(w.get(i));
}
return a;
}
}
·····X1·····
···················································································································································································
one hundred and two time manipulation(时间操作)
将查出来的list集合转成json数据的时候,发现时间数据变成时间戳了 @JSONField(format = “yyyy-MM-dd HH:mm:ss”)
import com.alibaba.fastjson.annotation.JSONField;
在实体类加注解如下:
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime msgDateTime;
格式化 SimpleDateFormat
public static void main(String[] args){
Date date = new Date();
String strDateFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.println(sdf.format(date));
}
当前时间
public static void main(String[] args){
SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
sdf.applyPattern("yyyy-MM-dd HH:mm:ss a");// a为am/pm的标记
Date date = new Date();// 获取当前时间
System.out.println("现在时间:" + sdf.format(date)); // 输出已经格式化的现在时间(24小时制)
}
年,月,日…
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DATE);
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
int dow = cal.get(Calendar.DAY_OF_WEEK);
int dom = cal.get(Calendar.DAY_OF_MONTH);
int doy = cal.get(Calendar.DAY_OF_YEAR);
System.out.println("当期时间: " + cal.getTime());
System.out.println("日期: " + day);
System.out.println("月份: " + month);
System.out.println("年份: " + year);
System.out.println("一周的第几天: " + dow); // 星期日为一周的第一天输出为 1,星期一输出为 2,以此类推
System.out.println("一月中的第几天: " + dom);
System.out.println("一年的第几天: " + doy);
}
时间戳转换成时间
public static void main(String[] args){
Long timeStamp = System.currentTimeMillis(); //获取当前时间戳
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp)))); // 时间戳转换成时间
System.out.println("格式化结果:" + sd);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒");
String sd2 = sdf2.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
System.out.println("格式化结果:" + sd2);
}
yyyy:年
MM:月
dd:日
hh:1~12小时制(1-12)
HH:24小时制(0-23)
mm:分
ss:秒
S:毫秒
E:星期几
D:一年中的第几天
F:一月中的第几个星期(会把这个月总共过的天数除以7)
w:一年中的第几个星期
W:一月中的第几星期(会根据实际情况来算)
a:上下午标识
k:和HH差不多,表示一天24小时制(1-24)
K:和hh差不多,表示一天12小时制(0-11)
z:表示时区
时间段 例:8:00 < nowDate < 17:00
class test {
/**
*分为上午和下午
* @param nowTime 当前时间
* @param amBeginTime 上午开始时间
* @param amEndTime 上午结束时间
* @param pmBeginTime 下午开始时间
* @param pmEndTime 下午结束时间
* @return
*/
public static boolean timeCalendar(Date nowTime, Date amBeginTime, Date amEndTime, Date pmBeginTime, Date pmEndTime) {
//设置当前时间
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
//设置开始时间
Calendar amBegin = Calendar.getInstance();
amBegin.setTime(amBeginTime);//上午开始时间
Calendar pmBegin = Calendar.getInstance();
pmBegin.setTime(pmBeginTime);//下午开始时间
//设置结束时间
Calendar amEnd = Calendar.getInstance();
amEnd.setTime(amEndTime);//上午结束时间
Calendar pmEnd = Calendar.getInstance();
pmEnd.setTime(pmEndTime);//下午结束时间
//处于开始时间之后,和结束时间之前的判断
if ((date.after(amBegin) && date.before(amEnd)) || (date.after(pmBegin) && date.before(pmEnd))) {
return true;
} else {
return false;
}
}
/**
* 只有一个时间段
* @param nowTime
* @param beginTime
* @param endTime
* @return boolean
*/
public static boolean timeCalendar(Date nowTime, Date beginTime, Date endTime) {
//设置当前时间
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
//设置开始时间
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);//开始时间
//设置结束时间
Calendar end = Calendar.getInstance();
end.setTime(endTime);//结束时间
//处于开始时间之后,和结束时间之前的判断
if((date.after(begin) && date.before(end))) {
return true;
} else {
return false;
}
}
/**
* 时间工具
* @param HHmm
* @return
*/
public static Date timeTool(String HHmm) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
Date date = df.parse(HHmm); //可设置的当前时间
return date;
}
/**
* 当前时间
* @return
*/
public static Date nowDate() throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
Date nowDate =df.parse(df.format(new Date())); //当前时间
return nowDate;
}
/**
* 在时间段之后
* @param nowTime
* @param beginTime
* @return boolean
*/
public static boolean afterTimeCalendar(Date nowTime, Date beginTime) {
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);
if(( date.after(begin))) {
return true;
} else {
return false;
}
}
/**
* 在时间段之前
* @param nowTime
* @param beginTime
* @return boolean
*/
public static boolean beforeTimeCalendar(Date nowTime, Date beginTime) {
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);
if(( date.before(begin))) {
return true;
} else {
return false;
}
}
public static void main(String[] args) throws ParseException {
Date am0 = timeTool("7:00"); //上午开始时间
Date am1 = timeTool("12:00"); //上午结束时间
Date pm0 = timeTool("12:00"); //下午开始时间
Date pm1 = timeTool("19:00"); //下午结束时间
Date testTime1 = timeTool("8:15");
boolean b1 = timeCalendar(testTime1, am0, am1, pm0, pm1);
boolean b2 = timeCalendar(nowDate(), am0, am1, pm0, pm1); //分上午和下午 7:00~12:00 ,12:00~19:00
System.out.println("分上午和下午 \n测试时间:"+b1+"\n当前时间:"+b2 +"\n");
Date testTime2= timeTool("17:29");
boolean b3 = timeCalendar(testTime2, timeTool("7:00"), timeTool("19:00"));
boolean b4 = timeCalendar(nowDate(), timeTool("7:00"), timeTool("19:00")); //不区分 上午和下午 7~19:00
System.out.println("不区分上午和下午 \n测试时间:"+b3+"\n当前时间:"+b4 +"\n");
Date testTime3= timeTool("17:29");
boolean b5 = beforeTimeCalendar(testTime3, timeTool("8:00"));
boolean b6 = afterTimeCalendar(testTime3, timeTool("8:00"));
System.out.println("是否在8点时间之前:"+ b5 + "\n是否在8点时间之后:"+b6 +"\n");
}
}
/**
* @param time 时分秒格式 转换 秒数 (HH:mm:ss → ss ,举例: 12:34:56 → 45296 )
* @return 秒数
*/
public static long getSecond(String time) {
long s = 0;
if (time.length() == 8) { //时分秒格式00:00:00
int index1 = time.indexOf(":");
int index2 = time.indexOf(":", index1 + 1);
s = Integer.parseInt(time.substring(0, index1)) * 3600;//小时
s += Integer.parseInt(time.substring(index1 + 1, index2)) * 60;//分钟
s += Integer.parseInt(time.substring(index2 + 1));//秒
}
if (time.length() == 5) {//分秒格式00:00
s = Integer.parseInt(time.substring(time.length() - 2)); //秒 后两位肯定是秒
s += Integer.parseInt(time.substring(0, 2)) * 60; //分钟
}
return s;
}
/**
* @param str 秒数 转换 时分秒格式( ss → HH:mm:ss ,举例: 45296 → 12:34:56 )
* @return 时分秒格式 00:00:00
*/
public static String getSecondString(String str) {
Integer second = Integer.valueOf(str);
String h1 = null;
String m1 = null;
String s1 = null;
if (second < 60) {
return "00" + ":" + "00" + str;
}
if (60 <= second && second < 3600) {
Integer m = second / 60;
if (0 <= m && m < 10) {
m1 = "0" + m;
} else {
m1 = m.toString();
}
Integer s = second % 60;
if (0 <= s && s < 10) {
s1 = "0" + s;
} else {
s1 = s.toString();
}
return "00" + ":" + m1 + ":" + s1;
}
if (second >= 3600) {
Integer h = second / 3600;
if (0 <= h && h < 10) {
h1 = "0" + h;
} else {
h1 = h.toString();
}
Integer m = (second % 3600) / 60;
if (0 <= m && m < 10) {
m1 = "0" + m;
} else {
m1 = m.toString();
}
Integer s = (second % 3600) % 60;
if (0 <= s && s < 10) {
s1 = "0" + s;
} else {
s1 = s.toString();
}
return h1 + ":" + m1 + ":" + s1;
}
return null;
}
···················································································································································································
one hundred and three Of All the Ways (方法)
重载
class MyClass {
int height;
MyClass() {
System.out.println("无参数构造函数");
height = 4;
}
MyClass(int i) {
System.out.println("房子高度为 " + i + " 米");
height = i;
}
void info() {
System.out.println("房子高度为 " + height + " 米");
}
void info(String s) {
System.out.println(s + ": 房子高度为 " + height + " 米");
}
}
public class MainClass {
public static void main(String[] args) {
MyClass t = new MyClass(3);
t.info();
t.info("重载方法");
//重载构造函数
new MyClass();
}
}
重载 输出数组元素
public class MainClass {
public static void printArray(Integer[] inputArray) {
for (Integer element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void printArray(Double[] inputArray) {
for (Double element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void printArray(Character[] inputArray) {
for (Character element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void main(String args[]) {
Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("输出整型数组:");
printArray(integerArray);
System.out.println("\n输出双精度型数组:");
printArray(doubleArray);
System.out.println("\n输出字符型数组:");
printArray(characterArray);
}
}
汉诺塔算法
1.有三根杆子A,B,C。A杆上有若干碟子
2.每次移动一块碟子,小的只能叠在大的上面
3.把所有碟子从A杆全部移到C杆上
public static void main(String[] args) {
int nDisks = 3;
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from, char inter, char to) {
if (topN == 1){
System.out.println("Disk 1 from "
+ from + " to " + to);
}else {
doTowers(topN - 1, from, to, inter);
System.out.println("Disk "
+ topN + " from " + from + " to " + to);
doTowers(topN - 1, inter, from, to);
}
}
斐波那契数列
指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368……
特别指出:第0项是0,第1项是第一个1。
这个数列从第三项开始,每一项都等于前两项之和。
public static void main(String[] args) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
阶乘
一个正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,并且有0的阶乘为1。自然数n的阶乘写作n!。
亦即n!=1×2×3×…×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n。
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
覆盖 ※
方法重载与方法覆盖区别如下:
方法重载(Overloading):如果有两个方法的方法名相同,但参数不一致,哪么可以说一个方法是另一个方法的重载。
方法覆盖(Overriding):如果在子类中定义一个方法,其名称、返回类型及参数签名正好与父类中某个方法的名称、返回类型及参数签名相匹配,那么可以说,子类的方法覆盖了父类的方法。
public class Findareas{
public static void main (String []agrs){
Figure f= new Figure(10 , 10);
Rectangle r= new Rectangle(9 , 5);
Figure figref;
figref=f;
System.out.println("Area is :"+figref.area());
figref=r;
System.out.println("Area is :"+figref.area());
}
}
class Figure{
double dim1;
double dim2;
Figure(double a , double b) {
dim1=a;
dim2=b;
}
Double area() {
System.out.println("Inside area for figure.");
return(dim1*dim2);
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a ,b);
}
Double area() {
System.out.println("Inside area for rectangle.");
return(dim1*dim2);
}
}
instanceof
instanceof 是 Java 的一个二元操作符,类似于 ==,>,< 等操作符。
instanceof 是 Java 的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回 boolean 的数据类型。
public static void main(String[] args) {
Object testObject = new ArrayList();
displayObjectClass(testObject);
}
public static void displayObjectClass(Object o) {
if (o instanceof Vector)
System.out.println("对象是 java.util.Vector 类的实例");
else if (o instanceof ArrayList)
System.out.println("对象是 java.util.ArrayList 类的实例");
else
System.out.println("对象是 " + o.getClass() + " 类的实例");
}
break
Java break 语句可以直接强行退出当前的循环,忽略循环体中任何其他语句和循环条件测试。
public static void main(String[] args) {
int[] intary = { 99,12,22,34,45,67,5678,8990 };
int no = 5678;
int i = 0;
boolean found = false;
for ( ; i < intary.length; i++) {
if (intary[i] == no) {
found = true;
break;
}
}
if (found) {
System.out.println(no + " 元素的索引位置在: " + i);
}
else {
System.out.println(no + " 元素不在数组中");
}
}
continue
Java continue 语句语句用来结束当前循环,并进入下一次循环,即仅仅这一次循环结束了,不是所有循环结束了,后边的循环依旧进行。
public static void main(String[] args) {
StringBuffer searchstr = new StringBuffer("hello how are you. ");
int length = searchstr.length();
int count = 0;
for (int i = 0; i < length; i++) {
if (searchstr.charAt(i) != 'h')
continue;
count++;
searchstr.setCharAt(i, 'h');
}
System.out.println("发现 " + count
+ " 个 h 字符");
System.out.println(searchstr);
}
标签(Label)
Java 中的标签是为循环设计的,是为了在多重循环中方便的使用 break 和coutinue 。
public static void main(String[] args) {
String strSearch = "This is the string in which you have to search for a substring.";
String substring = "substring";
boolean found = false;
int max = strSearch.length() - substring.length();
testlbl:
for (int i = 0; i <= max; i++) {
int length = substring.length();
int j = i;
int k = 0;
while (length-- != 0) {
if(strSearch.charAt(j++) != substring.charAt(k++)){
continue testlbl;
}
}
found = true;
break testlbl;
}
if (found) {
System.out.println("发现子字符串。");
}
else {
System.out.println("字符串中没有发现子字符串。");
}
}
enum 和 switch 语句使用
Java 创建枚举类型要使用 enum 关键字,隐含了所创建的类型都是 java.lang.Enum 类的子类
enum Car {
lamborghini,tata,audi,fiat,honda
}
public class Main {
public static void main(String args[]){
Car c;
c = Car.tata;
switch(c) {
case lamborghini:
System.out.println("你选择了 lamborghini!");
break;
case tata:
System.out.println("你选择了 tata!");
break;
case audi:
System.out.println("你选择了 audi!");
break;
case fiat:
System.out.println("你选择了 fiat!");
break;
case honda:
System.out.println("你选择了 honda!");
break;
default:
System.out.println("我不知道你的车型。");
break;
}
}
}
Enum(枚举)构造函数及方法的使用
enum Car {
lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;
Car(int p) {
price = p;
}
int getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]){
System.out.println("所有汽车的价格:");
for (Car c : Car.values())
System.out.println(c + " 需要 "
+ c.getPrice() + " 千美元。");
}
}
for 和 foreach循环使用
for 语句比较简单,用于循环数据。
for循环执行的次数是在执行前就确定的。语法格式如下:
for(初始化; 布尔表达式; 更新) {
//代码语句
}
foreach语句是java5的新特征之一,在遍历数组、集合方面,foreach为开发人员提供了极大的方便。
foreach 语法格式如下:
for(元素类型t 元素变量x : 遍历对象obj){
引用了x的java语句;
}
public static void main(String[] args) {
int[] intary = { 1,2,3,4};
forDisplay(intary);
foreachDisplay(intary);
}
public static void forDisplay(int[] a){
System.out.println("使用 for 循环数组");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void foreachDisplay(int[] data){
System.out.println("使用 foreach 循环数组");
for (int a : data) {
System.out.print(a+ " ");
}
}
Varargs
Java1.5提供了一个叫varargs的新功能,就是可变长度的参数。
“Varargs"是"variable number of arguments"的意思。有时候也被简单的称为"variable arguments”
定义实参个数可变的方法:只要在一个形参的"类型"与"参数名"之间加上三个连续的".“(即”…",英文里的句中省略号),就可以让它和不确定个实参相匹配。
public class Main {
static int sumvarargs(int... intArrays){
int sum, i;
sum=0;
for(i=0; i< intArrays.length; i++) {
sum += intArrays[i];
}
return(sum);
}
public static void main(String args[]){
int sum=0;
sum = sumvarargs(new int[]{10,12,33});
System.out.println("数字相加之和为: " + sum);
}
}
重载(overloading)方法中使用 Varargs
public class Main {
static void vaTest(int ... no) {
System.out.print("vaTest(int ...): "
+ "参数个数: " + no.length +" 内容: ");
for(int n : no)
System.out.print(n + " ");
System.out.println();
}
static void vaTest(boolean ... bl) {
System.out.print("vaTest(boolean ...) " +
"参数个数: " + bl.length + " 内容: ");
for(boolean b : bl)
System.out.print(b + " ");
System.out.println();
}
static void vaTest(String msg, int ... no) {
System.out.print("vaTest(String, int ...): " +
msg +"参数个数: "+ no.length +" 内容: ");
for(int n : no)
System.out.print(n + " ");
System.out.println();
}
public static void main(String args[]){
vaTest(1, 2, 3);
vaTest("测试: ", 10, 20);
vaTest(true, false, false);
}
}
···················································································································································································
one hundred and four Print various graphics (图形)
菱形
public class Diamond {
public static void main(String[] args) {
print(8); // 输出 8 行的菱形
}
public static void print(int size) {
if (size % 2 == 0) {
size++; // 计算菱形大小
}
for (int i = 0; i < size / 2 + 1; i++) {
for (int j = size / 2 + 1; j > i + 1; j--) {
System.out.print(" "); // 输出左上角位置的空白
}
for (int j = 0; j < 2 * i + 1; j++) {
System.out.print("*"); // 输出菱形上半部边缘
}
System.out.println(); // 换行
}
for (int i = size / 2 + 1; i < size; i++) {
for (int j = 0; j < i - size / 2; j++) {
System.out.print(" "); // 输出菱形左下角空白
}
for (int j = 0; j < 2 * size - 1 - 2 * i; j++) {
System.out.print("*"); // 输出菱形下半部边缘
}
System.out.println(); // 换行
}
}
}
九九乘法表
public class MultiplicationTable {
public static void main(String[] args) {
for(int i=1;i<=9;i++) {
for(int j=1;j<=i;j++) {
System.out.print(j+"×"+i+"="+i*j+"\t");// \t 跳到下一个TAB位置
}
System.out.println();
}
}
}
三角形
class Demo{
public static void main(String[] args){
for(int i=1;i<=5;i++){
for(int j=5; i<=j; j--)
System.out.print(" ");
for(int j=1; j<=i; j++)
System.out.print("*");
for(int j=1; j<i; j++)
System.out.print("*");
System.out.println();
}
}
}
倒立的三角形
public class InvertedTriangle {
public static void main(String[] args) {
//打印倒立的三角形
for (int m = 1; m <= 4; m++) {
//打印空格
for (int n = 0; n <= m; n++) {
System.out.print(" ");
}
//打印*
for (int x = 1; x <= 7 -2 * (m - 1); x++) {
System.out.print("*");
}
System.out.println();
}
}
}
平行四边形
public class Parallelogram {
public static void main(String[] args) {
//外层循环 每次打出一个*
for (int i = 1; i <=5; i++) {
//填充空格
for (int j = 1; j <= 5 - i; j++) {
System.out.print(" ");
}
//内层循环 每次打印一个*
for (int k = 1; k <= 5; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
矩形
public class Rect {
public static void main(String[] args) {
//外层循环 每次输出一行*
for (int i = 1; i <= 5; i++) {
System.out.print("*");
//内层循环 每次输出一个*
for (int j = 1; j <= 5; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
···················································································································································································
one hundred and five file operations(文件操作)
文件写入
使用 write() 方法向文件写入内容:
public class Main {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("runoob.txt"));
out.write("菜鸟教程");
out.close();
System.out.println("文件创建成功!");
} catch (IOException e) {
}
}
}
读取文件内容
使用 readLine() 方法来读取文件 test.log 内容,其中 test.log 文件内容为:www.百度.com
public class Main {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader("test.log"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
System.out.println(str);
} catch (IOException e) {
}
}
}
文件删除
使用 delete() 方法将文件删除:
public class Main
{
public static void main(String[] args)
{
try{
File file = new File("c:\\test.txt");
if(file.delete()){
System.out.println(file.getName() + " 文件已被删除!");
}else{
System.out.println("文件删除失败!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
复制
使用 BufferedWriter 类的 read 和 write 方法将文件内容复制到另一个文件:
public class Main {
public static void main(String[] args) throws Exception {
BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
out1.write("string to be copied\n");
out1.close();
InputStream in = new FileInputStream(new File("srcfile"));
OutputStream out = new FileOutputStream
(new File("destnfile"));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
String str;
while ((str = in1.readLine()) != null) {
System.out.println(str);
}
in1.close();
}
}
向文件中追加数据
使用 filewriter 方法向文件中追加数据:
public class Main {
public static void main(String[] args) throws Exception {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
out.write("aString1\n");
out.close();
out = new BufferedWriter(new FileWriter("filename",true));
out.write("aString2");
out.close();
BufferedReader in = new BufferedReader(new FileReader("filename"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
catch (IOException e) {
System.out.println("exception occoured"+ e);
}
}
}
创建临时文件
使用 File 类的 createTempFile(String prefix, String suffix); 方法在默认临时目录来创建临时文件,参数 prefix 为前缀,suffix 为后缀:
public class Main {
public static void main(String[] args) throws Exception {
File temp = File.createTempFile("testrunoobtmp", ".txt");
System.out.println("文件路径: "+temp.getAbsolutePath());
temp.deleteOnExit();
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("aString");
System.out.println("临时文件已创建:");
out.close();
}
}
也可以使用 createTempFile(String prefix, String suffix, File directory) 中的 directory 参数来指定临时文件的目录:
public class Main {
public static void main(String[] args) {
File f = null;
try {
// 创建临时文件
f = File.createTempFile("tmp", ".txt", new File("C:/"));
// 输出绝对路径
System.out.println("File path: "+f.getAbsolutePath());
// 终止后删除临时文件
f.deleteOnExit();
// 创建临时文件
f = File.createTempFile("tmp", null, new File("D:/"));
// 输出绝对路径
System.out.print("File path: "+f.getAbsolutePath());
// 终止后删除临时文件
f.deleteOnExit();
} catch(Exception e) {
// 如果有错误输出内容
e.printStackTrace();
}
}
}
修改文件最后的修改日期
使用 File 类的 fileToChange.lastModified() 和 fileToChange setLastModified() 方法来修改文件最后的修改日期:
public class Main {
public static void main(String[] args) throws Exception {
File fileToChange = new File("C:/myjavafile.txt");
fileToChange.createNewFile();
Date filetime = new Date(fileToChange.lastModified());
System.out.println(filetime.toString());
System.out.println(fileToChange.setLastModified(System.currentTimeMillis()));
filetime = new Date(fileToChange.lastModified());
System.out.println(filetime.toString());
}
}
获取文件大小
使用 File 类的 file.exists() 和 file.length() 方法来获取文件大小,以字节计算(1KB=1024字节 ):
public class Main {
public static long getFileSize(String filename) {
File file = new File(filename);
if (!file.exists() || !file.isFile()) {
System.out.println("文件不存在");
return -1;
}
return file.length();
}
public static void main(String[] args) {
long size = getFileSize("c:/java.txt");
System.out.println("java.txt文件大小为: " + size);
}
}
文件重命名
使用 File 类的 oldName.renameTo(newName) 方法来重命名文件。
执行以下程序前需要在当前目录下创建测试文件 runoob-test.txt。
public class RunoobTest {
public static void main(String[] args) throws IOException {
// 旧的文件或目录
File oldName = new File("./runoob-test.txt");
// 新的文件或目录
File newName = new File("./runoob-test-2.txt");
if (newName.exists()) { // 确保新的文件名不存在
throw new java.io.IOException("file exists");
}
if(oldName.renameTo(newName)) {
System.out.println("已重命名");
} else {
System.out.println("Error");
}
}
}
设置文件只读
使用 File 类的 file.setReadOnly() 和 file.canWrite() 方法来设置文件只读:
public class Main {
public static void main(String[] args) {
File file = new File("C:/java.txt");
System.out.println(file.setReadOnly());
System.out.println(file.canWrite());
}
}
检测文件是否存在
使用 File 类的 file.exists() 方法来检测文件是否存在:
public class Main {
public static void main(String[] args) {
File file = new File("C:/java.txt");
System.out.println(file.exists());
}
}
在指定目录中创建文件
使用 File 类的 file.createTempFile() 方法在指定目录中创建文件:
public class Main {
public static void main(String[] args) throws Exception {
File file = null;
File dir = new File("C:/");
file = File.createTempFile
("JavaTemp", ".javatemp", dir);
System.out.println(file.getPath());
}
}
获取文件修改时间
使用 File 类的 file.lastModified() 方法来获取文件最后的修改时间
public class Main {
public static void main(String[] args) {
File file = new File("Main.java");
Long lastModified = file.lastModified();
Date date = new Date(lastModified);
System.out.println(date);
}
}
创建文件
File 类的 File() 构造函数和 file.createNewFile() 方法来创建一个新的文件
public class Main {
public static void main(String[] args) {
try{
File file = new File("C:/myfile.txt");
if(file.createNewFile())
System.out.println("文件创建成功!");
else
System.out.println("出错了,该文件已经存在。");
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
文件路径比较
使用 File 类的 filename.compareTo (another filename) 方法来比较两个文件路径是否在同一个目录下:
public class Main {
public static void main(String[] args) {
File file1 = new File("C:/File/demo1.txt");
File file2 = new File("C:/java/demo1.txt");
if(file1.compareTo(file2) == 0) {
System.out.println("文件路径一致!");
} else {
System.out.println("文件路径不一致!");
}
}
}
·····X0·····
//*1 //操作系统不同 则目录结构不同 文件之间所使用的的 斜杠 与 反斜杠 不同
//文件的读取,一次性读完,但是会改变文件的结构,每行以 , 分隔,头尾分别加 [ ] ,不建议使用。
public static void main(String[] args) throws IOException {
File file = new File("D:\\9_test\\drillMainWay\\drill\\drill_JobCall.txt");
List<String> strings = Files.readLines(file, StandardCharsets.UTF_8);
System.out.println(strings);
}
//*2
//文件的读取,一次性读完,推荐使用
public static void main(String[] args) throws IOException {
Path path = Paths.get("D:\\9_test\\drillMainWay\\drill\\drill_JobCall.txt");
byte[] data = java.nio.file.Files.readAllBytes(path);
String result = new String(data, "utf-8");
System.out.println(result);
}
//*3 //操作系统不同 则目录结构不同 文件之间所使用的的 斜杠 与 反斜杠 不同
//文件的读取,需要以 ??? 结尾。
/*
如下以:
</schmoll_mes_message>
/结尾。
*/
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("D:\\9_test\\drillMainWay\\drill\\drill_JobCall.txt"));
String strIn;
String strtxt = "";
while ((strIn = in.readLine()) != null) {
if(strIn.equals("</schmoll_mes_message>")){
break;
}
strtxt = strtxt + strIn + "\n";
}
strtxt = strtxt + "</schmoll_mes_message>";
System.out.println(strtxt);
}
package tests;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
*文件夹目录下面的所有子文件,追加写入txt
*/
public class FileUtil {
/**
* @Description: 读取文件数据 可以修改编码
*/
public static List<String> readFileData(String Filename) {
List<String> fileData=new ArrayList<String>();
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(Filename.trim())), "utf-8");
BufferedReader streamReader = new BufferedReader(reader);
String line="";
while ((line = streamReader.readLine()) != null) {
fileData.add(line + "\n");
}
reader.close();
streamReader.close();
} catch (Exception exception) {
System.out.println(exception);
}
return fileData;
}
/**
* @Description: 写文件信息 可以修改编码
*/
public static void writerFile(String filePath,List<String> data) {
readFileData("");
try {
File file = new File(filePath);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file),"utf-8");
data.forEach(d -> {
try {
outputStreamWriter.write(d);
} catch (IOException e) {
e.printStackTrace();
}
});
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/**
*
* @param filePath 文件夹目录
* @param writerFile 要保存的txt文件
* 将文件夹目录里面的所有子文件,追加全都写入txt文件
*/
public static void writerFiles(String filePath,String writerFile){
File dir = new File(filePath);
String[] children = dir.list();
List<String> fileData=new ArrayList<String>();
if (children == null) {
System.out.println("该目录不存在");
}else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
List<String> strings = FileUtil.readFileData(filePath + "\\" + filename);
strings.forEach(d -> {
fileData.add(d);
});
}
FileUtil.writerFile(writerFile,fileData);
}
}
public static void main(String[] argv) throws Exception {
//单个txt写入单个txt
writerFile("D:\\BaiduNetdiskDownload\\002.txt",readFileData("D:\\BaiduNetdiskDownload\\001.txt"));
//文件夹下面的所有子文件 追加写入txt
writerFiles("D:\\BaiduNetdiskDownload\\从一个湖开始的进化_白衣见雪","D:\\BaiduNetdiskDownload\\004.txt");
}
}
/**
*依次搜索路径,当某个文件不存在跳出,并返回不存在的路径,否则返回空。
*/
public static String NoUrl(String url){
if(url.isEmpty()){
url = "D:\\9_test\\txt\\0001\\0002\\1.txt";
}
String nourl = "";
String[] split = url.split("\\\\");
String s = "";
for (int i=0;i<split.length;i++) {
if(i>=0){
s+=split[i]+"\\";
String str_url = s.substring(0,s.lastIndexOf("\\"));
File file = new File(str_url);
if(!file.exists()){
System.out.println("不存在:"+file);
nourl = file.toString();
break;
}
}
}
return nourl;
}
FileMethod
public class FileMethod {
public static void main(String[] args) {
machine("123123");
}
public static void machine(String conent) {
try {
String path1 =System.getProperty("user.dir") + File.separator + "log1.log";
String path2 = System.getProperty("user.dir") + File.separator + "log2.log";
File file1 = new File(path1);
File file2 = new File(path2);
if(!file1.exists()){
file1.createNewFile();
}
if(!file2.exists()){
file2.createNewFile();
}
FileInputStream fileInputStream = new FileInputStream((path1));
int available1 = fileInputStream.available();
if(available1 > 5*1024*1024){ //文件1大于5M (5*1024*1024)
if(file2.exists()){
file2.delete();
fileInputStream.close();
file1.renameTo(new File(path2));
}
if(!file1.exists()){
file1.createNewFile();
method(path1,"\n" + new Date() + "\n" + conent);
}
}else {
method(path1,"\n" + new Date() + "\n" +conent);
}
}catch (Exception e){
e.printStackTrace();
}
}
private static void method(String file, String conent) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true)));
out.write(conent+"\r\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
·····X1·····
···················································································································································································
one hundred and six Directory operation(目录操作)
递归创建目录
使用 File 类的 mkdirs() 实现递归创建目录 :
public class Main {
public static void main(String[] args) {
String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i";
File file = new File(directories);
boolean result = file.mkdirs();
System.out.println("Status = " + result);
}
}
删除目录
使用 File 类的 ofdir.isDirectory(), dir.list() 和 deleteDir() 方法在一个个删除文件后删除目录 :
public class Main {
public static void main(String[] argv) throws Exception {
// 删除当前目录下的 test 目录
deleteDir(new File("./test"));
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir
(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
if(dir.delete()) {
System.out.println("目录已被删除!");
return true;
} else {
System.out.println("目录删除失败!");
return false;
}
}
}
判断目录是否为空
使用 File 类的 file.isDirectory() 和 file.list() 方法来判断目录是否为空
public class Main
{
public static void main(String[] args)
{
File file = new File("./testdir"); // 当前目录下的 testdir目录
if(file.isDirectory()){
if(file.list().length>0){
System.out.println("目录不为空!");
}else{
System.out.println("目录为空!");
}
}else{
System.out.println("这不是一个目录!");
}
}
}
判断文件是否隐藏
使用 File 类的 file.isHidden() 方法来判断文件是否隐藏:
public class Main {
public static void main(String[] args) {
File file = new File("C:/Demo.txt");
System.out.println(file.isHidden());
}
}
获取目录大小
使用 File 类的 FileUtils.sizeofDirectory(File Name) 来获取目录的大小:
public class Main {
public static void main(String[] args) {
long size = FileUtils.sizeOfDirectory(new File("C:/test"));
System.out.println("Size: " + size + " bytes");
}
}
在指定目录中查找文件
使用 File 类的 dir.list() 方法在指定目录中查找所有文件列表:
public class Main {
public static void main(String[] argv) throws Exception {
File dir = new File("../java");
String[] children = dir.list();
if (children == null) {
System.out.println("该目录不存在");
}
else {
for (int i = 0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
获取文件的上级目录
使用 File 类的 file.getParent() 方法来获取文件的上级目录:
public class Main {
public static void main(String[] args) {
File file = new File("C:/File/demo.txt");
String strParentDirectory = file.getParent();
System.out.println("文件的上级目录为 : " + strParentDirectory);
}
}
获取目录最后修改时间
使用 File 类的 file.lastModified() 方法来获取目录的最后修改时间:
public class Main {
public static void main(String[] args) {
File file = new File("C://FileIO//demo.txt");
System.out.println("最后修改时间:" + new Date(file.lastModified()));
}
}
打印目录结构
使用 File 类的 file.getName() 和 file.listFiles() 方法来打印目录结构:
public class FileUtil {
public static void main(String[] a)throws IOException{
showDir(1, new File("d:\\Java"));
}
static void showDir(int indent, File file) throws IOException {
for (int i = 0; i < indent; i++)
System.out.print('-');
System.out.println(file.getName());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
showDir(indent + 4, files[i]);
}
}
}
遍历指定目录下的所有目录
使用 File 类的 list 方法来遍历指定目录下的所有目录:
class Main {
public static void main(String[] args) {
File dir = new File("F:");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("目录不存在或它不是一个目录");
}
else {
for (int i=0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}
输出指定目录下的所有文件
使用 File 类的 list 方法来输出指定目录下的所有文件:
class Main {
public static void main(String[] args) {
File dir = new File("C:");
String[] children = dir.list();
if (children == null) {
System.out.println( "目录不存在或它不是一个目录");
}
else {
for (int i=0; i< children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
在指定目录中查找文件
在 C 盘中查找以字母 ‘b’ 开头的所有文件:
class Main {
public static void main(String[] args) {
File dir = new File("C:");
FilenameFilter filter = new FilenameFilter() {
public boolean accept
(File dir, String name) {
return name.startsWith("b");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("目录不存在或它不是一个目录");
}
else {
for (int i=0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
查看系统根目录
使用 File 类的 listRoots() 方法来输出系统所有根目录:
class Main{
public static void main(String[] args){
File[] roots = File.listRoots();
System.out.println("系统所有根目录:");
for (int i=0; i < roots.length; i++) {
System.out.println(roots[i].toString());
}
}
}
查看当前工作目录
使用 System 的 getProperty() 方法来获取当前的工作目录:
class Main {
public static void main(String[] args) {
String curDir = System.getProperty("user.dir");
System.out.println("你当前的工作目录为 :" + curDir);
}
}
遍历目录
使用 File 类的 dir.isDirectory() 和 dir.list() 方法来遍历目录:
public class Main {
public static void main(String[] argv) throws Exception {
System.out.println("遍历目录");
File dir = new File("/www/java"); //要遍历的目录
visitAllDirsAndFiles(dir);
}
public static void visitAllDirsAndFiles(File dir) {
System.out.println(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}
}
·····X0·····
如果当前目录下没有logs文件夹,则创建这个文件夹
File logs = new File(curDir+"\\logs");
if(!logs.exists()){ // 如果当前目录下没有logs文件夹,则创建这个文件夹
logs.mkdir();
}
static int flag = 1;//用来判断文件是否删除成功
/**
*删除文件夹下所以文件,包含自身
* @param file
*/
public static void deFis(File file){
//判断文件不为null或文件目录存在
if (file == null || !file.exists()){
flag = 0;
System.out.println("文件删除失败,请检查文件路径是否正确");
return;
}
//取得这个目录下的所有子文件对象
File[] files = file.listFiles();
//遍历该目录下的文件对象
for (File f: files){
//打印文件名
String name = file.getName();
System.out.println(name);
//判断子目录是否存在子目录,如果是文件则删除
if (f.isDirectory()){
deFis(f);
}else {
f.delete();
}
}
file.delete(); //删除自身文件夹
}
/**
* 文件0001为已存储文件
* 文件0002为正在写入文件
* 文件最大存储数量为 i
* 下面是:从0002文件夹 开始写入 1txt 写到 9txt 每写入一次内容,重新创建txt,
* 写满9个保存到0001文件夹。
* 然后 从0002 开始重新写入,写满9个 把0001文件夹覆盖。 以此类推。
* @throws IOException
*
*/
public static void str() throws IOException {
File file = null;
FileWriter fw = null;
File f1 = new File("D:\\9_test\\txt\\0001");
File f2 = new File("D:\\9_test\\txt\\0002");
if(!f2.exists()){ // 如果当前目录下没有0002文件夹,则创建这个文件夹
f2.mkdir();
}
for(int i=1;i<10;i++){ //最大文件数量 i
file = new File(f2+"\\"+i+".txt");
if(i==9){
System.out.println("新一轮");
deFis(f1); // 删除 0001文件夹 包含自身
f2.renameTo(f1); //把 0002重命名为0001
if(!f2.exists()){ // 如果当前目录下没有0002文件夹
f2.mkdir(); //则重新创建这个文件夹
}
i=1;
break;
}
try {
if (!file.exists()) {
file.createNewFile();
if(fw!=null){
fw.close();
}
break; //如果存在就新创建一个文件,跳出,不会一次性创建99个文件
}
fw = new FileWriter(file); //向文件中写内容
fw.write(" function initTable() public {\n" +
" info[0]=\"repository1\";\n" +
" info[1]=\"tablename\";\n");
for(int j=2;j<i+2;j++){
fw.write(" info["+j+"]=\"data"+(j-1)+"\";\n");
}
fw.write(" }\n" + "\n" + "}");
fw.flush();
System.out.println("写数据成功!");
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fw != null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
if(fw!=null){
fw.close();
}
}
public static void main(String[] args) throws IOException {
str();
}
·····X1·····
···················································································································································································
one hundred and seven exception handling(异常处理)
异常处理方法
使用 System 类的 System.err.println() 来展示异常的处理方法:
class ExceptionDemo
{
public static void main(String[] args) {
try {
throw new Exception("My Exception");
} catch (Exception e) {
System.err.println("Caught Exception");
System.err.println("getMessage():" + e.getMessage());
System.err.println("getLocalizedMessage():" + e.getLocalizedMessage());
System.err.println("toString():" + e);
System.err.println("printStackTrace():");
e.printStackTrace();
}
}
}
多个异常处理(多个catch)
1,声明异常时,建议声明更为具体的异常,这样可以处理的更具体
2,对方声明几个异常,就对应几个catch块, 如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面
class Demo
{
int div(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException//在功能上通过throws的关键字声明该功能可能出现问题
{
int []arr = new int [a];
System.out.println(arr[4]);//制造的第一处异常
return a/b;//制造的第二处异常
}
}
class ExceptionDemo
{
public static void main(String[]args) //throws Exception
{
Demo d = new Demo();
try
{
int x = d.div(4,0);//程序运行截图中的三组示例 分别对应此处的三行代码
//int x = d.div(5,0);
//int x = d.div(4,1);
System.out.println("x="+x);
}
catch (ArithmeticException e)
{
System.out.println(e.toString());
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
}
catch (Exception e)//父类 写在此处是为了捕捉其他没预料到的异常 只能写在子类异常的代码后面
//不过一般情况下是不写的
{
System.out.println(e.toString());
}
System.out.println("Over");
}
}
Finally的用法
Java 中的 Finally 关键一般与try一起使用,在程序进入try块之后,无论程序是因为异常而中止或其它方式返回终止的,finally块的内容一定会被执行
使用 finally 通过 e.getMessage() 来捕获异常(非法参数异常):
public class ExceptionDemo2 {
public static void main(String[] argv) {
new ExceptionDemo2().doTheWork();
}
public void doTheWork() {
Object o = null;
for (int i=0; i<5; i++) {
try {
o = makeObj(i);
}
catch (IllegalArgumentException e) {
System.err.println
("Error: ("+ e.getMessage()+").");
return;
}
finally {
System.err.println("都已执行完毕");
if (o==null)
System.exit(0);
}
System.out.println(o);
}
}
public Object makeObj(int type)
throws IllegalArgumentException {
if (type == 1)
throw new IllegalArgumentException
("不是指定的类型: " + type);
return new Object();
}
}
使用 catch 来处理异常的方法:
public class Main {
public static void main (String args[]) {
int array[]={20,20,40};
int num1=15,num2=10;
int result=10;
try{
result = num1/num2;
System.out.println("结果为 " +result);
for(int i =5;i >=0; i--) {
System.out.println ("数组的元素值为 " +array[i]);
}
}
catch (Exception e) {
System.out.println("触发异常 : "+e);
}
}
}
多线程异常处理
class MyThread extends Thread{
public void run(){
System.out.println("Throwing in " +"MyThread");
throw new RuntimeException();
}
}
class Main {
public static void main(String[] args){
MyThread t = new MyThread();
t.start();
try{
Thread.sleep(1000);
}
catch (Exception x){
System.out.println("Caught it" + x);
}
System.out.println("Exiting main");
}
}
获取异常的堆栈信息
使用异常类的 printStack() 方法来获取堆栈信息:
public class Main{
public static void main (String args[]){
int array[]={20,20,40};
int num1=15,num2=10;
int result=10;
try{
result = num1/num2;
System.out.println("The result is" +result);
for(int i =5; i>=0; i--) {
System.out.println("The value of array is" +array[i]);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
重载方法异常处理
public class Main {
double method(int i) throws Exception{
return i/0;
}
boolean method(boolean b) {
return !b;
}
static double method(int x, double y) throws Exception {
return x + y ;
}
static double method(double x, double y) {
return x + y - 3;
}
public static void main(String[] args) {
Main mn = new Main();
try{
System.out.println(method(10, 20.0));
System.out.println(method(10.0, 20));
System.out.println(method(10.0, 20.0));
System.out.println(mn.method(10));
}
catch (Exception ex){
System.out.println("exception occoure: "+ ex);
}
}
}
链试异常
使用多个 catch 来处理链试异常:
public class Main {
public static void main (String args[])throws Exception {
int n=20,result=0;
try{
result=n/0;
System.out.println("结果为"+result);
}
catch(ArithmeticException ex){
System.out.println("发算术异常: "+ex);
try {
throw new NumberFormatException();
}
catch(NumberFormatException ex1) {
System.out.println("手动抛出链试异常 : "+ex1);
}
}
}
}
自定义异常
通过继承 Exception 来实现自定义异常:
class WrongInputException extends Exception { // 自定义的类
WrongInputException(String s) {
super(s);
}
}
class Input {
void method() throws WrongInputException {
throw new WrongInputException("Wrong input"); // 抛出自定义的类
}
}
class TestInput {
public static void main(String[] args){
try {
new Input().method();
}
catch(WrongInputException wie) {
System.out.println(wie.getMessage());
}
}
}
···················································································································································································
one hundred and eight data structure(数据结构)
数字求和运算
使用do…while结构求0~100的整数数字之和:
public class Main {
public static void main(String[] args) {
int limit=100;
int sum=0;
int i=1;
do
{
sum=sum+i;
i++;
}
while(i<=limit);
System.out.println("sum="+sum);
}
}
利用堆栈将中缀表达式转换成后缀表达式
使用堆栈进行表达式的堆栈将中缀(Infix)表达式转换成后缀(postfix)表达式:
public class InToPost {
private Stack theStack;
private String input;
private String output = "";
public InToPost(String in) {
input = in;
int stackSize = input.length();
theStack = new Stack(stackSize);
}
public String doTrans() {
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
switch (ch) {
case '+':
case '-':
gotOper(ch, 1);
break;
case '*':
case '/':
gotOper(ch, 2);
break;
case '(':
theStack.push(ch);
break;
case ')':
gotParen(ch);
break;
default:
output = output + ch;
break;
}
}
while (!theStack.isEmpty()) {
output = output + theStack.pop();
}
System.out.println(output);
return output;
}
public void gotOper(char opThis, int prec1) {
while (!theStack.isEmpty()) {
char opTop = theStack.pop();
if (opTop == '(') {
theStack.push(opTop);
break;
}
else {
int prec2;
if (opTop == '+' || opTop == '-')
prec2 = 1;
else
prec2 = 2;
if (prec2 < prec1) {
theStack.push(opTop);
break;
}
else
output = output + opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char ch){
while (!theStack.isEmpty()) {
char chx = theStack.pop();
if (chx == '(')
break;
else
output = output + chx;
}
}
public static void main(String[] args)
throws IOException {
String input = "1+2*4/5-7+3/6";
String output;
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans();
System.out.println("Postfix is " + output + '\n');
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
在链表(LinkedList)的开头和结尾添加元素
用 LinkedList 类的 addFirst() 和 addLast() 方法在链表的开头和结尾添加元素:
public class Main {
public static void main(String[] args) {
LinkedList<String> lList = new LinkedList<String>();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
System.out.println(lList);
lList.addFirst("0");
System.out.println(lList);
lList.addLast("6");
System.out.println(lList);
}
}
获取链表(LinkedList)的第一个和最后一个元素
使用 LinkedList 类的 linkedlistname.getFirst() 和 linkedlistname.getLast() 来获取链表的第一个和最后一个元素:
public class Main {
public static void main(String[] args) {
LinkedList<String> lList = new LinkedList<String>();
lList.add("100");
lList.add("200");
lList.add("300");
lList.add("400");
lList.add("500");
System.out.println("链表的第一个元素是:" + lList.getFirst());
System.out.println("链表的最后一个元素是:" + lList.getLast());
}
}
删除链表中的元素
使用 clear() 方法来删除链表中的元素:
public class Main {
public static void main(String[] args) {
LinkedList<String> lList = new LinkedList<String>();
lList.add("1");
lList.add("8");
lList.add("6");
lList.add("4");
lList.add("5");
System.out.println(lList);
lList.subList(2, 4).clear();
System.out.println(lList);
}
}
获取链表的元素
使用 top() 和 pop() 方法来获取链表的元素:
public class Main {
private LinkedList list = new LinkedList();
public void push(Object v) {
list.addFirst(v);
}
public Object top() {
return list.getFirst();
}
public Object pop() {
return list.removeFirst();
}
public static void main(String[] args) {
Main stack = new Main();
for (int i = 30; i < 40; i++)
stack.push(new Integer(i));
System.out.println(stack.top());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
获取向量元素的索引值
使用 Collections 类的 sort() 方法对向量进行排序并使用 binarySearch() 方法来获取向量元素的索引值:
public class Main {
public static void main(String[] args) {
Vector v = new Vector();
v.add("X");
v.add("M");
v.add("D");
v.add("A");
v.add("O");
Collections.sort(v);
System.out.println(v);
int index = Collections.binarySearch(v, "D");
System.out.println("元素索引值为 : " + index);
}
}
栈的实现
用户如何通过创建用于插入元素的自定义函数 push() 方法和用于弹出元素的 pop() 方法来实现栈:
public class MyStack {
private int maxSize;
private long[] stackArray;
private int top;
public MyStack(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;
}
public long pop() {
return stackArray[top--];
}
public long peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public static void main(String[] args) {
MyStack theStack = new MyStack(10);
theStack.push(10);
theStack.push(20);
theStack.push(30);
theStack.push(40);
theStack.push(50);
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
链表元素查找
使用 linkedlistname.indexof(element) 和 linkedlistname.Lastindexof(elementname) 方法在链表中获取元素第一次和最后一次出现的位置:
public class Main {
public static void main(String[] args) {
LinkedList lList = new LinkedList();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
lList.add("2");
System.out.println("元素 2 第一次出现的位置:" + lList.indexOf("2"));
System.out.println("元素 2 最后一次出现的位置:"+ lList.lastIndexOf("2"));
}
}
压栈出栈的方法实现字符串反转
使用用户自定义的方法 StringReverserThroughStack() 来实现字符串反转:
public class StringReverserThroughStack {
private String input;
private String output;
public StringReverserThroughStack(String in) {
input = in;
}
public String doRev() {
int stackSize = input.length();
Stack theStack = new Stack(stackSize);
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
theStack.push(ch);
}
output = "";
while (!theStack.isEmpty()) {
char ch = theStack.pop();
output = output + ch;
}
return output;
}
public static void main(String[] args)
throws IOException {
String input = "www.w3cschool.cc";
String output;
StringReverserThroughStack theReverser =
new StringReverserThroughStack(input);
output = theReverser.doRev();
System.out.println("反转前: " + input);
System.out.println("反转后: " + output);
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
队列(Queue)用法
队列是一种特殊的线性表,它只允许在表的前端进行删除操作,而在表的后端进行插入操作。
LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。
public class Main {
public static void main(String[] args) {
//add()和remove()方法在失败的时候会抛出异常(不推荐)
Queue<String> queue = new LinkedList<String>();
//添加元素
queue.offer("a");
queue.offer("b");
queue.offer("c");
queue.offer("d");
queue.offer("e");
for(String q : queue){
System.out.println(q);
}
System.out.println("===");
System.out.println("poll="+queue.poll()); //返回第一个元素,并在队列中删除
for(String q : queue){
System.out.println(q);
}
System.out.println("===");
System.out.println("element="+queue.element()); //返回第一个元素
for(String q : queue){
System.out.println(q);
}
System.out.println("===");
System.out.println("peek="+queue.peek()); //返回第一个元素
for(String q : queue){
System.out.println(q);
}
}
}
获取向量的最大元素
使用 Vector 类的 v.add() 方法及 Collection 类的 Collections.max() 来获取向量的最大元素:
public class Main {
public static void main(String[] args) {
Vector v = new Vector();
v.add(new Double("3.4324"));
v.add(new Double("3.3532"));
v.add(new Double("3.342"));
v.add(new Double("3.349"));
v.add(new Double("2.3"));
Object obj = Collections.max(v);
System.out.println("最大元素是:"+obj);
}
}
链表修改
使用 listname.add() 和 listname.set() 方法来修改链接中的元素:
public class Main {
public static void main(String[] a) {
LinkedList officers = new LinkedList();
officers.add("B");
officers.add("B");
officers.add("T");
officers.add("H");
officers.add("P");
System.out.println(officers);
officers.set(2, "M");
System.out.println(officers);
}
}
旋转向量
使用 swap() 函数来旋转向量:
public class Main {
public static void main(String[] args) {
Vector<String> v = new Vector();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
System.out.println(v);
Collections.swap(v, 0, 4);
System.out.println("旋转后");
System.out.println(v);
}
}
int a = 10;
int b = 4;
//短路或 一个成立,后面的不运行了
if (a > 0 || (b++) > 4){
System.out.println("a > 0 | (b++) > 4");
System.out.println(b); //用来判断后面的b++是否被执行
}
//逻辑或 所有的都运行
if (a > 0 | (b++) > 4){
System.out.println("a > 0 | (b++) > 4后b的值为:");
System.out.println(b); //用来判断后面的b++是否被执行
}
//短路与 一个成立,后面的不运行了
if (a > 100 && (b++) <5){
}
System.out.println("a < 100 && (b++) <5后b的值为:");
System.out.println(b); //用来判断后面的b++是否被执行
//逻辑与 所有的都运行
if (a > 100 & (b++) <5){
}
System.out.println("a < 100 & (b++) <5后b的值为:");
System.out.println(b); //用来判断后面的b++是否被执行
}
···················································································································································································
one hundred and nine set(集合)
数组转集合
使用 Java Util 类的 Arrays.asList(name) 方法将数组转换为集合:
public class ArrayToCollection{
public static void main(String args[])
throws IOException{
int n = 5; // 5 个元素
String[] name = new String[n];
for(int i = 0; i < n; i++){
name[i] = String.valueOf(i);
}
List<String> list = Arrays.asList(name);
System.out.println();
for(String li: list){
String str = li;
System.out.print(str + " ");
}
}
}
集合比较
将字符串转换为集合并使用 Collection 类的 Collection.min() 和 Collection.max() 来比较集合中的元素:
class Main {
public static void main(String[] args) {
String[] coins = { "Penny", "nickel", "dime", "Quarter", "dollar" };
Set<String> set = new TreeSet<String>();
for (int i = 0; i < coins.length; i++) {
set.add(coins[i]);
}
System.out.println(Collections.min(set));
System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));
for (int i = 0; i <= 10; i++) {
System.out.print("-");
}
System.out.println("");
System.out.println(Collections.max(set));
System.out.println(Collections.max(set, String.CASE_INSENSITIVE_ORDER));
}
}
HashMap遍历
使用 Collection 类的 iterator() 方法来遍历集合:
public class Main {
public static void main(String[] args) {
HashMap< String, String> hMap =
new HashMap< String, String>();
hMap.put("1", "1st");
hMap.put("2", "2nd");
hMap.put("3", "3rd");
Collection cl = hMap.values();
Iterator itr = cl.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
集合长度
使用 Collections 类 的collection.add() 来添加数据并使用 collection.size()来计算集合的长度:
public class Main {
public static void main(String [] args) {
System.out.println( "集合实例!\n" );
int size;
HashSet collection = new HashSet ();
String str1 = "Yellow", str2 = "White", str3 =
"Green", str4 = "Blue";
Iterator iterator;
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("集合数据: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
if (collection.isEmpty()){
System.out.println("集合是空的");
}
else{
System.out.println( "集合长度: " + size);
}
System.out.println();
}
}
集合打乱顺序
使用 Collections 类 Collections.shuffle() 方法来打乱集合元素的顺序:
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
list.add(new Integer(i));
System.out.println("打乱前:");
System.out.println(list);
for (int i = 1; i < 6; i++) {
System.out.println("第" + i + "次打乱:");
Collections.shuffle(list);
System.out.println(list);
}
}
}
集合遍历
如何遍历从Collection接口延伸出的List、Set和以键值对形式作存储的Map类型的集合,以下我们分别使用了普通for,增强型的 for ,iterator 等方式来遍历集合:
List与Set类型集合的遍历
public class Main {
public static void main(String[] args) {
// List集合的遍历
listTest();
// Set集合的遍历
setTest();
}
private static void setTest() {
Set<String> set = new HashSet<String>();
set.add("JAVA");
set.add("C");
set.add("C++");
// 重复数据添加失败
set.add("JAVA");
set.add("JAVASCRIPT");
// 使用iterator遍历set集合
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String value = it.next();
System.out.println(value);
}
// 使用增强for循环遍历set集合
for(String s: set){
System.out.println(s);
}
}
// 遍历list集合
private static void listTest() {
List<String> list = new ArrayList<String>();
list.add("菜");
list.add("鸟");
list.add("教");
list.add("程");
list.add("www.runoob.com");
// 使用iterator遍历
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String value = it.next();
System.out.println(value);
}
// 使用传统for循环进行遍历
for (int i = 0, size = list.size(); i < size; i++) {
String value = list.get(i);
System.out.println(value);
}
// 使用增强for循环进行遍历
for (String value : list) {
System.out.println(value);
}
}
}
集合反转
使用 Collection 和 Listiterator 类的 listIterator() 和 collection.reverse() 方法来反转集合中的元素:
class Main {
public static void main(String[] args) {
String[] coins = { "A", "B", "C", "D", "E" };
List l = new ArrayList();
for (int i = 0; i < coins.length; i++)
l.add(coins[i]);
ListIterator liter = l.listIterator();
System.out.println("反转前");
while (liter.hasNext())
System.out.println(liter.next());
Collections.reverse(l);
liter = l.listIterator();
System.out.println("反转后");
while (liter.hasNext())
System.out.println(liter.next());
}
}
删除集合中指定元素
使用 Collection 类的 collection.remove() 方法来删除集合中的指定的元素:
public class Main {
public static void main(String [] args) {
System.out.println( "集合实例!\n" );
int size;
HashSet collection = new HashSet ();
String str1 = "Yellow", str2 = "White", str3 =
"Green", str4 = "Blue";
Iterator iterator;
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("集合数据: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
collection.remove(str2);
System.out.println("删除之后 [" + str2 + "]\n");
System.out.print("现在集合的数据是: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
System.out.println("集合大小: " + size + "\n");
}
}
只读集合
使用 Collection 类的 Collections.unmodifiableList() 方法来设置集合为只读:
public class Main {
public static void main(String[] argv)
throws Exception {
List stuff = Arrays.asList(new String[] { "a", "b" });
List list = new ArrayList(stuff);
list = Collections.unmodifiableList(list);
try {
list.set(0, "new value");
}
catch (UnsupportedOperationException e) {
}
Set set = new HashSet(stuff);
set = Collections.unmodifiableSet(set);
Map map = new HashMap();
map = Collections.unmodifiableMap(map);
System.out.println("集合现在是只读");
}
}
集合输出
使用 Java Util 类的 tMap.keySet(),tMap.values() 和 tMap.firstKey() 方法将集合元素输出:
public class Main{
public static void main(String[] args) {
System.out.println("TreeMap 实例!\n");
TreeMap tMap = new TreeMap();
tMap.put(1, "Sunday");
tMap.put(2, "Monday");
tMap.put(3, "Tuesday");
tMap.put(4, "Wednesday");
tMap.put(5, "Thursday");
tMap.put(6, "Friday");
tMap.put(7, "Saturday");
System.out.println("TreeMap 键:"
+ tMap.keySet());
System.out.println("TreeMap 值:"
+ tMap.values());
System.out.println("键为 5 的值为: " + tMap.get(5)+ "\n");
System.out.println("第一个键: " + tMap.firstKey()
+ " Value: "
+ tMap.get(tMap.firstKey()) + "\n");
System.out.println("最后一个键: " + tMap.lastKey()
+ " Value: "+ tMap.get(tMap.lastKey()) + "\n");
System.out.println("移除第一个数据: "
+ tMap.remove(tMap.firstKey()));
System.out.println("现在 TreeMap 键为: "
+ tMap.keySet());
System.out.println("现在 TreeMap 包含: "
+ tMap.values() + "\n");
System.out.println("移除最后一个数据: "
+ tMap.remove(tMap.lastKey()));
System.out.println("现在 TreeMap 键为: "
+ tMap.keySet());
System.out.println("现在 TreeMap 包含: "
+ tMap.values());
}
}
集合转数组
用 Java Util 类的 list.add() 和 list.toArray() 方法将集合转为数组:
public class Main{
public static void main(String[] args){
List<String> list = new ArrayList<String>();
list.add("菜");
list.add("鸟");
list.add("教");
list.add("程");
list.add("www.runoob.com");
String[] s1 = list.toArray(new String[0]);
for(int i = 0; i < s1.length; ++i){
String contents = s1[i];
System.out.print(contents);
}
}
}
List 循环移动元素
使用 Collections 类的 rotate() 来循环移动元素,方法第二个参数指定了移动的起始位置:
public class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six".split(" "));
System.out.println("List :"+list);
Collections.rotate(list, 3);
System.out.println("rotate: " + list);
}
}
查找 List 中的最大最小值
使用 Collections 类的 max() 和 min() 方法来获取List中最大最小值:
public class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
System.out.println(list);
System.out.println("最大值: " + Collections.max(list));
System.out.println("最小值: " + Collections.min(list));
}
}
遍历 HashTable 的键值
使用 Hashtable 类的 keys() 方法来遍历输出键值:
public class Main {
public static void main(String[] args) {
Hashtable ht = new Hashtable();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.keys();
while (e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
使用 Enumeration 遍历 HashTable
使用 Enumeration 类的 hasMoreElements 和 nextElement 方法来遍历输出 HashTable 中的内容:
public class Main {
public static void main(String[] args) {
Hashtable ht = new Hashtable();
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
集合中添加不同类型元素
public class Main {
public static void main(String[] args) {
List lnkLst = new LinkedList();
lnkLst.add("element1");
lnkLst.add("element2");
lnkLst.add("element3");
lnkLst.add("element4");
displayAll(lnkLst);
List aryLst = new ArrayList();
aryLst.add("x");
aryLst.add("y");
aryLst.add("z");
aryLst.add("w");
displayAll(aryLst);
Set hashSet = new HashSet();
hashSet.add("set1");
hashSet.add("set2");
hashSet.add("set3");
hashSet.add("set4");
displayAll(hashSet);
SortedSet treeSet = new TreeSet();
treeSet.add("1");
treeSet.add("2");
treeSet.add("3");
treeSet.add("4");
displayAll(treeSet);
LinkedHashSet lnkHashset = new LinkedHashSet();
lnkHashset.add("one");
lnkHashset.add("two");
lnkHashset.add("three");
lnkHashset.add("four");
displayAll(lnkHashset);
Map map1 = new HashMap();
map1.put("key1", "J");
map1.put("key2", "K");
map1.put("key3", "L");
map1.put("key4", "M");
displayAll(map1.keySet());
displayAll(map1.values());
SortedMap map2 = new TreeMap();
map2.put("key1", "JJ");
map2.put("key2", "KK");
map2.put("key3", "LL");
map2.put("key4", "MM");
displayAll(map2.keySet());
displayAll(map2.values());
LinkedHashMap map3 = new LinkedHashMap();
map3.put("key1", "JJJ");
map3.put("key2", "KKK");
map3.put("key3", "LLL");
map3.put("key4", "MMM");
displayAll(map3.keySet());
displayAll(map3.values());
}
static void displayAll(Collection col) {
Iterator itr = col.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.print(str + " ");
}
System.out.println();
}
}
List 元素替换
使用 Collections 类的 replaceAll() 来替换List中所有的指定元素:
public class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
System.out.println("List :"+list);
Collections.replaceAll(list, "one", "hundrea");
System.out.println("replaceAll: " + list);
}
}
List 截取
使用 Collections 类的 indexOfSubList() 和 lastIndexOfSubList() 方法来查看子列表是否在列表中,并查看子列表在列表中所在的位置:
public class Main {
public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
System.out.println("List :"+list);
List sublist = Arrays.asList("three Four".split(" "));
System.out.println("子列表 :"+sublist);
System.out.println("indexOfSubList: "
+ Collections.indexOfSubList(list, sublist));
System.out.println("lastIndexOfSubList: "
+ Collections.lastIndexOfSubList(list, sublist));
}
}
·····X0·····
Vector、ArrayList、LinkedList
HashTable,HashMap,HashSet
TreeSet,TreeMap。
Vector,HashTable,LinkList是线程安全的。
public static void main(String[] args) {
//Vector、ArrayList、LinkedList,HashMap,HashSet,TreeSet,TreeMap,HashTable。
Vector vector = new Vector();
ArrayList arrayList = new ArrayList<>();
LinkedList linkedList = new LinkedList();
HashMap hashMap = new HashMap();
HashSet hashSet = new HashSet();
TreeSet treeSet = new TreeSet();
TreeMap treeMap = new TreeMap();
vector.add(0,"a");
arrayList.add(0,"b");
linkedList.add(0,"c");
hashMap.put("1","a");
hashSet.add("a");
treeSet.add("b");
treeMap.put("2","b");
System.out.println(vector+"\n"+ arrayList+"\n"+ linkedList+"\n"+ hashMap+"\n"+ hashSet+"\n"+ treeSet+"\n"+ treeMap);
}
public static void main(String[] args) {
//ArrayList
ArrayList list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
System.out.println("重复下标插入会当前下标的元素往后面移动,所以现在的元素大小为:" + list.size());
// 遍历方式
System.out.println(" for 下标循环");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
}
System.out.println("\n forEach 遍历");
for (Object str : list) {
System.out.print(str);
}
System.out.println("\n Itorator 迭代器遍历");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.print(it.next());
}
}
public static void main(String[] args) {
//HashMap map.keySet()方法;然后迭代保存了所有key的Set集合
Map map = new HashMap();
map.put("保质期", "3年");
map.put("产地", "上海");
map.put("价格", 39);
map.put("生产日期", "2015-09-16");
//获取map中键的集合;
Set set = map.keySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
//获取Set集合中每一个键值
String key = (String) iterator.next();
//根据键值取map中的键对应的值;
Object value = map.get(key);
System.out.println(key+":"+value);
}
}
public static void main(String[] args) {
//HashMap //map.entrySet()方法,然后迭代保存了Map.Entry的Set集合;
Map map = new HashMap();
map.put("保质期", "3年");
map.put("产地", "上海");
map.put("价格", 39);
map.put("生产日期", "2015-09-16");
//获得保存了map中键和值(Map.Entry)的Set集合;
Set set = map.entrySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
String key = (String) entry.getKey();
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
package com.example.xxx;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
class XxxApplicationTests {
@Test //ArrayList//底层是数组
void run1() {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("aaa");
System.out.println("下标为0,第一个元素:"+arrayList.get(0));
System.out.println("大小为:"+arrayList.size());
}
@Test //LinkedList 底层是双向链表
void run2() {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("aaa");
linkedList.add("bbb");
linkedList.add("ccc");
System.out.println(linkedList.toString());
linkedList.add(2, "lzs");
linkedList.addFirst("hahah");
System.out.println(linkedList.toString());
linkedList.remove(1);
linkedList.remove(2);
System.out.println(linkedList.toString());
}
@Test //iterator别倒错包
void run3() {
ArrayList linkedList = new ArrayList<String>();
linkedList.add("aaa");
linkedList.add("bbb");
linkedList.add("ccc");
System.out.println(linkedList.toString());
Iterator it = linkedList.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
@Test //增强for便利
void run4() {
ArrayList<String> linkedList = new ArrayList<String>();
linkedList.add("aaa");
linkedList.add("bbb");
linkedList.add("ccc");
for (String string : linkedList) {
System.out.println(string);
}
}
@Test //ArrayList iterator遍历中删除元素要注意的问题
void run5() {
ArrayList<String> linkedList = new ArrayList<String>();
linkedList.add("aaa");
linkedList.add("bbb");
linkedList.add("ccc");
linkedList.add("666");
Iterator<String> it = linkedList.iterator();
while (it.hasNext() != false) {
String st = it.next();
if (st == "lisi") {
it.remove();
}
}
System.out.print(linkedList);
}
@Test //ArrayList 倒序遍历
void run6() {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("aaa");
arrayList.add("bbb");
arrayList.add("ccc");
arrayList.add("ddd");
ListIterator<String> it1 = arrayList.listIterator(arrayList.size()); //制定起始位置
while (it1.hasPrevious()) {
System.out.print(it1.previous());
}
}
}
// List<Map> == List<Map<String,Object>>
public static void main(String[] args) {
List<Map<String,Object>> list=new ArrayList<>();
// List<Map> list=new ArrayList<>();
Map<String,Object> map=new HashMap<>();
map.put("id1",1);
list.add(map);
Map<String,Object> map2=new HashMap<>();
map2.put("id2",2);
list.add(map2);
Map<String,Object> map3=new HashMap<>();
map3.put("id3",3);
list.add(map3);
Map<String,Object> map4=new HashMap<>();
map4.put("id4",4);
list.add(map4);
Map<Set<String>, List<Map<String, Object>>> collect = list.stream().collect(Collectors.groupingBy(Map::keySet));
// Map<Set<String>, List<Map>> collect = list.stream().collect(Collectors.groupingBy(Map::keySet));
collect.forEach((k,v)->{
System.out.println();
System.out.println("k的值:");
k.forEach(System.out::println);
System.out.println("v的值:");
v.forEach(System.out::println);
});
}
·····X1·····
···················································································································································································
one hundred and ten Java Network instance(网络实例)
获取指定主机的IP地址
使用 InetAddress 类的 InetAddress.getByName() 方法来获取指定主机(网址)的IP地址:
public class GetIP {
public static void main(String[] args) {
InetAddress address = null;
try {
address = InetAddress.getByName("www.baidu.com");
}
catch (UnknownHostException e) {
System.exit(2);
}
System.out.println(address.getHostName() + "=" + address.getHostAddress());
System.exit(0);
}
}
查看端口是否已使用
public class Main {
public static void main(String[] args) {
Socket Skt;
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
for (int i = 0; i < 1024; i++) {
try {
System.out.println("查看 "+ i);
Skt = new Socket(host, i);
System.out.println("端口 " + i + " 已被使用");
}
catch (UnknownHostException e) {
System.out.println("Exception occured"+ e);
break;
}
catch (IOException e) {
}
}
}
}
获取本机ip地址及主机名
使用 InetAddress 类的 getLocalAddress() 方法获取本机ip地址及主机名:
public class Main {
public static void main(String[] args)
throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress:
"+addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
}
}
获取远程文件大小
public class Main {
public static void main(String[] args) throws Exception {
int size;
URL url = new URL("http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png");
URLConnection conn = url.openConnection();
size = conn.getContentLength();
if (size < 0)
System.out.println("无法获取文件大小。");
else
System.out.println("文件大小为:" + size + " bytes");
conn.getInputStream().close();
}
}
查看主机指定文件的最后修改时间
public class Main {
public static void main(String[] argv) throws Exception {
URL u = new URL("http://127.0.0.1/test/test.html");
URLConnection uc = u.openConnection();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
uc.setUseCaches(false);
long timestamp = uc.getLastModified();
System.out.println("test.html 文件最后修改时间 :" + ft.format(new Date(timestamp)));
}
}
Socket 实现多线程服务器程序
使用 Socket 类的 accept() 方法和 ServerSocket 类的 MultiThreadServer(socketname) 方法来实现多线程服务器程序:
public class MultiThreadServer implements Runnable {
Socket csocket;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
}
public static void main(String args[])
throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new MultiThreadServer(sock)).start();
}
}
public void run() {
try {
PrintStream pstream = new PrintStream
(csocket.getOutputStream());
for (int i = 100; i >= 0; i--) {
pstream.println(i +
" bottles of beer on the wall");
}
pstream.close();
csocket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
使用 Socket 连接到指定主机
使用 net.Socket 类的 getInetAddress() 方法来连接到指定主机:
public class WebPing {
public static void main(String[] args) {
try {
InetAddress addr;
Socket sock = new Socket("www.runoob.com", 80);
addr = sock.getInetAddress();
System.out.println("连接到 " + addr);
sock.close();
} catch (java.io.IOException e) {
System.out.println("无法连接 " + args[0]);
System.out.println(e);
}
}
}
网页抓取
使用 net.URL 类的 URL() 构造函数来抓取网页:
public class Main {
public static void main(String[] args)
throws Exception {
URL url = new URL("http://www.runoob.com");
BufferedReader reader = new BufferedReader
(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter
(new FileWriter("data.html"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
}
}
获取 URL响应头的日期信息
使用 HttpURLConnection 的 httpCon.getDate() 方法来获取 URL响应头的日期信息:
public class Main{
public static void main(String args[])
throws Exception {
URL url = new URL("http://www.runoob.com");
HttpURLConnection httpCon =
(HttpURLConnection) url.openConnection();
long date = httpCon.getDate();
if (date == 0)
System.out.println("无法获取信息。");
else
System.out.println("Date: " + new Date(date));
}
}
获取 URL 响应头信息
public class Main {
public static void main(String[] args) throws IOException{
URL url = new URL("http://www.runoob.com");
URLConnection conn = url.openConnection();
Map headers = conn.getHeaderFields();
Set<String> keys = headers.keySet();
for( String key : keys ){
String val = conn.getHeaderField(key);
System.out.println(key+" "+val);
}
System.out.println( conn.getLastModified() );
}
}
解析 URL
使用 net.URL 类的 url.getProtocol() ,url.getFile() 等方法来解析 URL 地址:
public class Main {
public static void main(String[] args)
throws Exception {
URL url = new URL("http://www.runoob.com/html/html-tutorial.html");
System.out.println("URL 是 " + url.toString());
System.out.println("协议是 " + url.getProtocol());
System.out.println("文件名是 " + url.getFile());
System.out.println("主机是 " + url.getHost());
System.out.println("路径是 " + url.getPath());
System.out.println("端口号是 " + url.getPort());
System.out.println("默认端口号是 "
+ url.getDefaultPort());
}
}
ServerSocket 和 Socket 通信实例
如何实现客户端发送消息到服务器,服务器接收到消息并读取输出,然后写出到客户端客户端接收到输出。
1、建立服务器端
服务器建立通信ServerSocket
服务器建立Socket接收客户端连接
建立IO输入流读取客户端发送的数据
建立IO输出流向客户端发送数据消息
public class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8888);
System.out.println("启动服务器....");
Socket s = ss.accept();
System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//读取客户端发送来的消息
String mess = br.readLine();
System.out.println("客户端:"+mess);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write(mess+"\n");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、建立客户端
创建Socket通信,设置通信服务器的IP和Port
建立IO输出流向服务器发送数据消息
建立IO输入流读取服务器发送来的数据消息
public class Client {
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1",8888);
//构建IO
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
//向服务器端发送一条消息
bw.write("测试客户端和服务器通信,服务器接收到消息返回到客户端\n");
bw.flush();
//读取服务器返回的消息
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String mess = br.readLine();
System.out.println("服务器:"+mess);
System.out.println("chinaunix,itpub,51cto,落伍者,蓝色理想,it写作社区,博客堂,it英雄榜,邪恶八进制,
Stack Overflow,Reddit,Google+ Communities,SitePoint,CodeProject,Treehouse,Hacker News,
DZone,Bytes,DaniWeb,Dream In Code,Tech.Pro,Pineapple,Lobsters,学优IT");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
InputStream和OutputStream:使用InputStream读取Socket输入流中的数据,使用OutputStream向Socket输出流中写入数据。
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
byte[] data = new byte[1024];
int len = is.read(data);
os.write(data, 0, len);
BufferedReader和PrintWriter:使用BufferedReader读取Socket输入流中的数据,使用PrintWriter向Socket输出流中写入数据。
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String data = reader.readLine();
writer.println(data);
DataInputStream和DataOutputStream:使用DataInputStream读取Socket输入流中的数据,使用DataOutputStream向Socket输出流中写入数据。
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
String data = dis.readUTF();
dos.writeUTF(data);
ObjectInputStream和ObjectOutputStream:使用ObjectInputStream读取Socket输入流中的对象数据,使用ObjectOutputStream向Socket输出流中写入对象数据。
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
Object data = ois.readObject();
oos.writeObject(data);
package http;
import java.io.*;
import java.net.Socket;
/**
* 与服务端交互正常 ,ClientSocket ,客户端
* 开启此线程在main方法中
* public static HttpClientSocket httpClientSocket;
* public Main(){ //main方法的初始化方法
httpClientSocket = new HttpClientSocket();
httpClientSocket.start();
System.out.println("ip+端口:"+"\n"+httpClientSocket.address + ":" + httpClientSocket.port);
}
*/
public class HttpClientSocket extends Thread{
public boolean bRun = true;
public Socket socket1;
public PrintStream outStream;
public BufferedReader in;
public InputStream input;
public String address = "127.0.0.1";
public int port = 8189;
private String strSocketNew = "";
public static String strFromMes = "";
@Override
public void run() {
while (true) {
if (socket1 != null && socket1.isConnected() && !socket1.isClosed()) {
bRun = true;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
outStream = new PrintStream(socket1.getOutputStream(),true, "gbk");
input = socket1.getInputStream();
in = new BufferedReader(new InputStreamReader(input));
} catch (Exception ie) {
}
while (bRun) {
try {
receive();
} catch (Exception ie) {
ie.printStackTrace();
}
}
} else {
try {
socket1 = new Socket(address, port);
System.out.println("已连接");
outStream = new PrintStream(socket1.getOutputStream(),true, "gbk");
} catch (IOException io) {
if (!strSocketNew.equalsIgnoreCase(io.getMessage())) {
strSocketNew = io.getMessage();
}
}
}
}
}
public void receive() {
try {
try{
Thread.sleep(5000);
socket1.sendUrgentData(0xFF);
} catch (Exception e){
e.printStackTrace();
socket1 = null;
bRun = false;
}
strFromMes = "";
String line;
while ((line = in.readLine()) != null) {
strFromMes += line + "\n";
if(line.equals("SMDATEND")){
break;
}
}
System.out.println(strFromMes);
} catch (IOException e) {
e.printStackTrace();
}
}
public String send(String StringIn) {
outStream.println(StringIn);
System.out.println(StringIn);
return null;
}
}
1 传送对象
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SocCie {
public static void main(String[] args) throws IOException {
Socket socket =new Socket("127.0.0.1",5005);
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
User user =new User("189421","123");
oos.writeObject(user);
oos.flush();
oos.close();
os.close();
socket.close();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocSer {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket serverSocket =new ServerSocket(5005);
Socket accept = serverSocket.accept();
InputStream is=accept.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
Object object = ois.readObject();
User user = (User)object;
System.out.println("账号:"+user.getUserNo()+"\n"+"密码:"+user.getUserPwd());
ois.close();
is.close();
serverSocket.close();
}
}
import java.io.Serializable;
public class User implements Serializable {
private String userNo;
private String userPwd;
public User(){}
public User(String userNo, String userPwd) {
this.userNo = userNo;
this.userPwd = userPwd;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}
2 ClientSocket ~~~ SocketServer
服务端
package SocketServer;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String[] args) {
try {
// 创建服务端socket
ServerSocket serverSocket = new ServerSocket(8089);
System.out.println("服务启动成功");
// 创建客户端socket
Socket socket = new Socket();
//循环监听等待客户端的连接
while(true){
// 监听客户端
socket = serverSocket.accept();
ServerThread thread = new ServerThread(socket);
thread.start();
InetAddress address=socket.getInetAddress();
// System.out.println("当前客户端的IP:"+address.getHostAddress());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ServerThread extends Thread{
private Socket socket = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
InputStream is=null;
InputStreamReader isr=null;
BufferedReader br=null;
OutputStream os=null;
PrintWriter pw=null;
try {
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String info = null;
while((info=br.readLine())!=null){
System.out.println("我是服务器,客户端说:"+info);
}
socket.shutdownInput();
os = socket.getOutputStream();
pw = new PrintWriter(os);
// pw.write("服务器欢迎你");
pw.write(AreYouThereRequestReply());
pw.write(InitialDataRequest());
pw.flush();
} catch (Exception e) {
// TODO: handle exception
} finally{
//关闭资源
try {
if(pw!=null)
pw.close();
if(os!=null)
os.close();
if(br!=null)
br.close();
if(isr!=null)
isr.close();
if(is!=null)
is.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String AreYouThereRequestReply(){
String str ="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<message>\n" +
"<header>\n" +
"<messagename>AreYouThereRequestReply</messagename>\n" +
"<transactionid>20181223121212789</transactionid>\n" +
"</header>\n" +
"<body>\n" +
" <eqp_id></eqp_id>\n" +
"<return_code></return_code>\n" +
"</body> \n" +
"<return>\n" +
"<returncode></returncode>\n" +
"<returnmessage></returnmessage>\n" +
"</return>\n" +
"</message>";
return str;
}
public static String InitialDataRequest(){
String str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<message>\n" +
"<header>\n" +
"<messagename>InitialDataRequest</messagename>\n" +
"<transactionid>20181223121212789</transactionid>\n" +
"</header>\n" +
"<body>\n" +
"<eqp_id></eqp_id>\n" +
"</body> \n" +
"<return>\n" +
"<returncode></returncode>\n" +
"<returnmessage></returnmessage>\n" +
"</return>\n" +
"</message>";
return str;
}
}
客户端
客户端
package mesAgent.customerClient.http;
import org.apache.log4j.Logger;
import java.io.*;
import java.net.Socket;
public class HttpClientSocket extends Thread{
private static final Logger logger = Logger.getLogger(HttpClientSocket.class);
public boolean bRun = true;
private boolean machineFlag = true;
public Socket socket1;
public PrintStream outStream;
public BufferedReader in;
public InputStream input;
public String address = "127.0.0.1";
public int port = 8089;
private String strSocketNew = "";
public String strFromMes = "";
@Override
public void run() {
while (true) {
if (socket1 != null && socket1.isConnected() && !socket1.isClosed()) {
bRun = true;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
outStream = new PrintStream(socket1.getOutputStream(),true, "gbk");
input = socket1.getInputStream();
in = new BufferedReader(new InputStreamReader(input));
} catch (Exception ie) {
}
while (bRun) {
try {
receive();
} catch (Exception ie) {
ie.printStackTrace();
}
}
} else {
try {
socket1 = new Socket(address, port);
outStream = new PrintStream(socket1.getOutputStream(),true, "gbk");
} catch (IOException io) {
if (!strSocketNew.equalsIgnoreCase(io.getMessage())) {
strSocketNew = io.getMessage();
}
}
}
}
}
//接收
public void receive() throws IOException {
try {
try{
Thread.sleep(5000);
socket1.sendUrgentData(0xFF);
} catch (Exception e){
e.printStackTrace();
socket1 = null;
bRun = false;
}
strFromMes = "";
String line;
while ((line = in.readLine()) != null) {
strFromMes += line + "\n";
// if (line.equals("SMDATEND")){
// if (strFromMes.contains("<cmd_type>WriteReply</cmd_type>") | strFromMes.contains("<cmd_type>ReadReply</cmd_type>")){
sendToMes(strFromMes);
// }else if (strFromMes.contains("<cmd_id>common.MachineTypePlate</cmd_id>") & machineFlag){
StyleProperties.machineText = strFromMes;
// machineFlag = false;
// }
sendToMes(strFromMes);
// System.out.println(strFromMes);
// strFromMes = "";
// }
}
if(strFromMes==null){
}else {
if(strFromMes.contains("AreYouThereRequestReply")){
System.out.println(strFromMes);
strFromMes="";
}
if(strFromMes.contains("InitialDataRequest")){
System.out.println(strFromMes);
strFromMes="";
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
//发送
public String send(String StringIn) {
outStream.println(StringIn);
System.out.println(StringIn);
return null;
}
// @Override
// public void run() {
// while (true){
// try {
// // 要发送给服务器的信息
// Socket client=null;
// client = new Socket("127.0.0.1", 8088);
// OutputStream os = client.getOutputStream();
// PrintWriter pw = new PrintWriter(os);
pw.write("客户端发送信息");
pw.write(CustomerClientImpl.request());
// pw.flush();
// client.shutdownOutput();
// // 从服务器接收的信息
// InputStream is = client.getInputStream();
// BufferedReader br = new BufferedReader(new InputStreamReader(is));
// String info = "";
// String message = "";
// while((info = br.readLine())!=null){
// System.out.println("我是客户端,服务器返回信息:"+info);
// message+=info;
// }
// if(message==null){
// }else {
// if(message.contains("AreYouThereRequestReply")){
// System.out.println(message);
// message="";
// }
// if(message.contains("InitialDataRequest")){
// System.out.println(message);
// message="";
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// }
public void str(){
}
// public static void ClientSocket(String message){
// try {
// // 和服务器创建连接
// Socket socket = new Socket("127.0.0.1",8088);
// // 要发送给服务器的信息
// PrintWriter pw = new PrintWriter(socket.getOutputStream());
// pw.write(message);
// pw.flush();
// socket.shutdownOutput();
// pw.close();
// socket.close();
// } catch (Exception e) {
// logger.error(e);
// e.printStackTrace();
// }
// }
// public static void Client2Socket(String message){
// try {
// Socket socket = new Socket("127.0.0.1", 8088);
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// PrintWriter pw = new PrintWriter(socket.getOutputStream());
// while(true){
// pw.println("小二说:"+br.readLine());
// pw.flush();
// }
// } catch (Exception e) {
// logger.error(e);
// e.printStackTrace();
// }
// }
public static void main(String[] args) {
//2
// ClientSocket("你好");
}
}
测试
test(测试)(先启动服务端 main 方法,再测试)
public static void main(String[] args) {
// System.out.println(getTimeMill());
HttpClientSocket httpClientSocket = new HttpClientSocket();
httpClientSocket.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
httpClientSocket.send("hello world");
}
···················································································································································································
one hundred and eleven thread(线程)
查看线程是否存活
通过继承 Thread 类并使用 isAlive() 方法来检测一个线程是否存活:
public class TwoThreadAlive extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}
public void printMsg() {
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}
public static void main(String[] args) {
TwoThreadAlive tt = new TwoThreadAlive();
tt.setName("Thread");
System.out.println("before start(), tt.isAlive()=" + tt.isAlive());
tt.start();
System.out.println("just after start(), tt.isAlive()=" + tt.isAlive());
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive());
}
}
获取当前线程名称
通过继承 Thread 类并使用 getName() 方法来获取当前线程名称:
public class TwoThreadGetName extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
printMsg();
}
}
public void printMsg() {
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}
public static void main(String[] args) {
TwoThreadGetName tt = new TwoThreadGetName();
tt.start();
for (int i = 0; i < 10; i++) {
tt.printMsg();
}
}
}
状态监测
通过继承 Thread 类并使用 currentThread.getName() 方法来监测线程的状态:
class MyThread extends Thread{
boolean waiting= true;
boolean ready= false;
MyThread() {
}
public void run() {
String thrdName = Thread.currentThread().getName();
System.out.println(thrdName + " starting.");
while(waiting)
System.out.println("waiting:"+waiting);
System.out.println("waiting...");
startWait();
try {
Thread.sleep(1000);
}
catch(Exception exc) {
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " terminating.");
}
synchronized void startWait() {
try {
while(!ready) wait();
}
catch(InterruptedException exc) {
System.out.println("wait() interrupted");
}
}
synchronized void notice() {
ready = true;
notify();
}
}
public class Main {
public static void main(String args[])
throws Exception{
MyThread thrd = new MyThread();
thrd.setName("MyThread #1");
showThreadStatus(thrd);
thrd.start();
Thread.sleep(50);
showThreadStatus(thrd);
thrd.waiting = false;
Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd) {
System.out.println(thrd.getName() + "Alive:=" + thrd.isAlive() + " State:=" + thrd.getState());
}
}
线程优先级设置
通过setPriority() 方法来设置线程的优先级:
public class SimplePriorities extends Thread {
private int countDown = 5;
private volatile double d = 0;
public SimplePriorities(int priority) {
setPriority(priority);
start();
}
public String toString() {
return super.toString() + ": " + countDown;
}
public void run() {
while(true) {
for(int i = 1; i < 100000; i++)
d = d + (Math.PI + Math.E) / (double)i;
System.out.println(this);
if(--countDown == 0) return;
}
}
public static void main(String[] args) {
new SimplePriorities(Thread.MAX_PRIORITY);
for(int i = 0; i < 5; i++)
new SimplePriorities(Thread.MIN_PRIORITY);
}
}
死锁及解决方法
死锁是这样一种情形:多个线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放。由于线程被无限期地阻塞,因此程序不可能正常终止。
java 死锁产生的四个必要条件:
1、互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用
2、不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。
3、请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的占有。
4、循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。
当上述四个条件都成立的时候,便形成死锁。当然,死锁的情况下如果打破上述任何一个条件,便可让死锁消失。下面用java代码来模拟一下死锁的产生。
解决死锁问题的方法是:一种是用synchronized,一种是用Lock显式锁实现。
public class LockTest {
public static String obj1 = "obj1";
public static String obj2 = "obj2";
public static void main(String[] args) {
LockA la = new LockA();
new Thread(la).start();
LockB lb = new LockB();
new Thread(lb).start();
}
}
class LockA implements Runnable{
public void run() {
try {
System.out.println(new Date().toString() + " LockA 开始执行");
while(true){
synchronized (LockTest.obj1) {
System.out.println(new Date().toString() + " LockA 锁住 obj1");
Thread.sleep(3000); // 此处等待是给B能锁住机会
synchronized (LockTest.obj2) {
System.out.println(new Date().toString() + " LockA 锁住 obj2");
Thread.sleep(60 * 1000); // 为测试,占用了就不放
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class LockB implements Runnable{
public void run() {
try {
System.out.println(new Date().toString() + " LockB 开始执行");
while(true){
synchronized (LockTest.obj2) {
System.out.println(new Date().toString() + " LockB 锁住 obj2");
Thread.sleep(3000); // 此处等待是给A能锁住机会
synchronized (LockTest.obj1) {
System.out.println(new Date().toString() + " LockB 锁住 obj1");
Thread.sleep(60 * 1000); // 为测试,占用了就不放
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
此时死锁产生。
为了解决这个问题,我们不使用显示的去锁,我们用信号量去控制。
信号量可以控制资源能被多少线程访问,这里我们指定只能被一个线程访问,就做到了类似锁住。而信号量可以指定去获取的超时时间,我们可以根据这个超时时间,去做一个额外处理。
对于无法成功获取的情况,一般就是重复尝试,或指定尝试的次数,也可以马上退出。
public class UnLockTest {
public static String obj1 = "obj1";
public static final Semaphore a1 = new Semaphore(1);
public static String obj2 = "obj2";
public static final Semaphore a2 = new Semaphore(1);
public static void main(String[] args) {
LockAa la = new LockAa();
new Thread(la).start();
LockBb lb = new LockBb();
new Thread(lb).start();
}
}
class LockAa implements Runnable {
public void run() {
try {
System.out.println(new Date().toString() + " LockA 开始执行");
while (true) {
if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {
System.out.println(new Date().toString() + " LockA 锁住 obj1");
if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {
System.out.println(new Date().toString() + " LockA 锁住 obj2");
Thread.sleep(60 * 1000); // do something
}else{
System.out.println(new Date().toString() + "LockA 锁 obj2 失败");
}
}else{
System.out.println(new Date().toString() + "LockA 锁 obj1 失败");
}
UnLockTest.a1.release(); // 释放
UnLockTest.a2.release();
Thread.sleep(1000); // 马上进行尝试,现实情况下do something是不确定的
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class LockBb implements Runnable {
public void run() {
try {
System.out.println(new Date().toString() + " LockB 开始执行");
while (true) {
if (UnLockTest.a2.tryAcquire(1, TimeUnit.SECONDS)) {
System.out.println(new Date().toString() + " LockB 锁住 obj2");
if (UnLockTest.a1.tryAcquire(1, TimeUnit.SECONDS)) {
System.out.println(new Date().toString() + " LockB 锁住 obj1");
Thread.sleep(60 * 1000); // do something
}else{
System.out.println(new Date().toString() + "LockB 锁 obj1 失败");
}
}else{
System.out.println(new Date().toString() + "LockB 锁 obj2 失败");
}
UnLockTest.a1.release(); // 释放
UnLockTest.a2.release();
Thread.sleep(10 * 1000); // 这里只是为了演示,所以tryAcquire只用1秒,而且B要给A让出能执行的时间,否则两个永远是死锁
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
获取线程id
使用 getThreadId() 方法获取线程id:
public class Main extends Object implements Runnable {
private ThreadID var;
public Main(ThreadID v) {
this.var = v;
}
public void run() {
try {
print("var getThreadID =" + var.getThreadID());
Thread.sleep(2000);
print("var getThreadID =" + var.getThreadID());
} catch (InterruptedException x) {
}
}
private static void print(String msg) {
String name = Thread.currentThread().getName();
System.out.println(name + ": " + msg);
}
public static void main(String[] args) {
ThreadID tid = new ThreadID();
Main shared = new Main(tid);
try {
Thread threadA = new Thread(shared, "threadA");
threadA.start();
Thread.sleep(500);
Thread threadB = new Thread(shared, "threadB");
threadB.start();
Thread.sleep(500);
Thread threadC = new Thread(shared, "threadC");
threadC.start();
} catch (InterruptedException x) {
}
}
}
class ThreadID extends ThreadLocal {
private int nextID;
public ThreadID() {
nextID = 10001;
}
private synchronized Integer getNewID() {
Integer id = new Integer(nextID);
nextID++;
return id;
}
protected Object initialValue() {
print("in initialValue()");
return getNewID();
}
public int getThreadID() {
Integer id = (Integer) get();
return id.intValue();
}
private static void print(String msg) {
String name = Thread.currentThread().getName();
System.out.println(name + ": " + msg);
}
}
线程挂起
public class SleepingThread extends Thread {
private int countDown = 5;
private static int threadCount = 0;
public SleepingThread() {
super("" + ++threadCount);
start();
}
public String toString() {
return "#" + getName() + ": " + countDown;
}
public void run() {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
try {
sleep(100);
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args)
throws InterruptedException {
for (int i = 0; i < 5; i++)
new SleepingThread().join();
System.out.println("线程已被挂起");
}
}
终止线程
Java中原来在Thread中提供了stop()方法来终止线程,但这个方法是不安全的,所以一般不建议使用。
使用interrupt方法来终端线程可分为两种情况:
(1)线程处于阻塞状态,如使用了sleep方法。
(2)使用while(!isInterrupted()){……}来判断线程是否被中断。
在第一种情况下使用interrupt方法,sleep方法将抛出一个InterruptedException例外,而在第二种情况下线程将直接退出。下面的代码演示了在第一种情况下使用interrupt方法。
public class ThreadInterrupt extends Thread
{
public void run()
{
try
{
sleep(50000); // 延迟50秒
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws Exception
{
Thread thread = new ThreadInterrupt();
thread.start();
System.out.println("在50秒之内按任意键中断线程!");
System.in.read();
thread.interrupt();
thread.join();
System.out.println("线程已经退出!");
}
}
生产者/消费者问题
生产者和消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一个存储空间,生产者向空间里存放数据,而消费者取用数据,如果不加以协调可能会出现以下情况:
存储空间已满,而生产者占用着它,消费者等着生产者让出空间从而去除产品,生产者等着消费者消费产品,从而向空间中添加产品。互相等待,从而发生死锁。
public class ProducerConsumerTest {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
}
catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
}
catch (InterruptedException e) {
}
}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("消费者 #" + this.number+ " got: " + value);
}
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("生产者 #" + this.number + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
获取线程状态
// Java 程序 - 演示线程状态
class thread implements Runnable
{
public void run()
{
// thread2 - 超时等待
try
{
Thread.sleep(1500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread1 while it called join() method on thread2 -"+
Test.thread1.getState());
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class Test implements Runnable
{
public static Thread thread1;
public static Test obj;
public static void main(String[] args)
{
obj = new Test();
thread1 = new Thread(obj);
// 创建 thread1,现在是初始状态
System.out.println("State of thread1 after creating it - " + thread1.getState());
thread1.start();
// thread1 - 就绪状态
System.out.println("State of thread1 after calling .start() method on it - " +
thread1.getState());
}
public void run()
{
thread myThread = new thread();
Thread thread2 = new Thread(myThread);
// 创建 thread1,现在是初始状态
System.out.println("State of thread2 after creating it - "+ thread2.getState());
thread2.start();
// thread2 - 就绪状态
System.out.println("State of thread2 after calling .start() method on it - " +
thread2.getState());
// moving thread1 to timed waiting state
try
{
//moving - 超时等待
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread2 after calling .sleep() method on it - "+
thread2.getState() );
try
{
// 等待 thread2 终止
thread2.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread2 when it has finished it's execution - " +
thread2.getState());
}
}
获取所有线程
使用 getName() 方法获取所有正在运行的线程:
public class Main extends Thread {
public static void main(String[] args) {
Main t1 = new Main();
t1.setName("thread1");
t1.start();
ThreadGroup currentGroup =
Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
for (int i = 0; i < noThreads; i++)
System.out.println("线程号:" + i + " = " + lstThreads[i].getName());
}
}
查看线程优先级
使用 getThreadId() 方法获取线程id:
public class Main extends Object {
private static Runnable makeRunnable() {
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
Thread t = Thread.currentThread();
System.out.println("in run() - priority="
+ t.getPriority()+ ", name=" + t.getName());
try {
Thread.sleep(2000);
}
catch (InterruptedException x) {
}
}
}
};
return r;
}
public static void main(String[] args) {
System.out.println("in main() - Thread.currentThread().getPriority()=" + Thread.currentThread().getPriority());
System.out.println("in main() - Thread.currentThread().getName()="+ Thread.currentThread().getName());
Thread threadA = new Thread(makeRunnable(), "threadA");
threadA.start();
try {
Thread.sleep(3000);
}
catch (InterruptedException x) {
}
System.out.println("in main() - threadA.getPriority()="+ threadA.getPriority());
}
}
中断线程
使用interrupt()方法来中断线程并使用 isInterrupted() 方法来判断线程是否已中断:
public class Main extends Object
implements Runnable {
public void run() {
try {
System.out.println("in run() - 将运行 work2() 方法");
work2();
System.out.println("in run() - 从 work2() 方法回来");
}
catch (InterruptedException x) {
System.out.println("in run() - 中断 work2() 方法");
return;
}
System.out.println("in run() - 休眠后执行");
System.out.println("in run() - 正常离开");
}
public void work2() throws InterruptedException {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
Thread.sleep(2000);
System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
}
}
}
public void work() throws InterruptedException {
while (true) {
for (int i = 0; i < 100000; i++) {
int j = i * 2;
}
System.out.println("A isInterrupted()=" + Thread.currentThread().isInterrupted());
if (Thread.interrupted()) {
System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted());
throw new InterruptedException();
}
}
}
public static void main(String[] args) {
Main si = new Main();
Thread t = new Thread(si);
t.start();
try {
Thread.sleep(2000);
}
catch (InterruptedException x) {
}
System.out.println("in main() - 中断其他线程");
t.interrupt();
System.out.println("in main() - 离开");
}
}
·····X0·····
package com.example.xxx;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class XxxApplicationTests {
//newSingleThreadExecutor:创建一个单线程的线程池,这个线程池只有一个线程在工作也就是相当于单线程串行执行所有任务。如果这个微医的线程因为异常而结束,那么会有一个新的线程来代替它。此线程池保证所有任务的的执行顺序按照任务的提交顺序执行。
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
final int j = i;
service.execute(() -> {
System.out.println(j + " " + Thread.currentThread().getName());
// 即使出错之后也不会停止运行,会创建一个新的线程来继续执行;
});
}
}
}
/**
* newFixedThreadPool:创建固定大小的线程池。每次提交一个任务就创建一个线程,知道线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行一场而结束那么线程池会补充一个新线程。
*/
class test1 {
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 0; i < 6; i++) {
service.execute(()->{
try {
TimeUnit.MILLISECONDS.sleep(500);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("Thread.currentThread().getName()→→→:"+"\n"+Thread.currentThread().getName());
});
}
System.out.println("service→→→:"+"\n"+service);
System.out.println("service.isTerminated()→→→:"+"\n"+service.isTerminated());
System.out.println("service.isShutdown()→→→:"+"\n"+service.isShutdown());
System.out.println("service→→→:"+"\n"+service);
TimeUnit.SECONDS.sleep(50);
System.out.println("service.isTerminated()→→→:"+"\n"+service.isTerminated());
System.out.println("service.isShutdown()→→→:"+"\n"+service.isShutdown());
System.out.println("service→→→:"+"\n"+service);
}
}
/**
newCachedThreadPool:创建一个可缓存的线程池。如果线程池大小超过了处理任务所需的线程,那么就会回收部分空闲(60s不执行任务)的线程,当任务书增加时,此线程池又可以智能的添加新线程来处理任务。此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。
*/
class test2 {
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newCachedThreadPool();
System.out.println(service);
for (int i = 0; i < 2; i++) {
service.execute(()->{
try {
TimeUnit.MILLISECONDS.sleep(500);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("Thread.currentThread().getName()→→→"+"\n"+Thread.currentThread().getName());
});
}
System.out.println("service→→→"+"\n"+service);
TimeUnit.SECONDS.sleep(8);
System.out.println("service→→→"+"\n"+service);
}
}
/**
* newScheduledThreadPool:创建一个大小无线的线程池。此线程池支持定时及周期性执行任务的要求
*/
class test3 {
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(4);
service.scheduleAtFixedRate(()->{
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("Thread.currentThread().getName()→→→"+"\n"+Thread.currentThread().getName());
},0,500, TimeUnit.MILLISECONDS);
}
}
·····X1·····
·····X0·····
3多线程,同步锁。(xy)
package test;
/**
线程的休眠,实现Runnable接口
*/
class test1 {
public static void main(String[] args) {
MyThread m1 = new MyThread("线程A"); //实例化MyThread对象
MyThread m2 = new MyThread("线程B");
Thread t1 = new Thread(m1); //实例化Thread对象
Thread t2 = new Thread(m2);
t1.start();//启动线程
t2.start();
}
static class MyThread implements Runnable{
private String name;
public MyThread(String name){
this.name = name;
}
@Override
public void run() {
for(int i=0;i<50;i++){
try {
Thread.sleep(500);//线程休眠
}catch (InterruptedException e){
}
System.out.println(name+"运行,i="+i);
}
}
}
}
/**
线程的强制运行,实现Runnable接口
*/
class test2 {
public static void main(String[] args) {
MyThread m1 = new MyThread("线程A"); //实例化MyThread对象
Thread t1 = new Thread(m1); //实例化Thread对象
t1.start();//启动线程
for(int i=0;i<50;i++){
if(i>10){
try {
t1.join(); //线程强制运行
}catch (InterruptedException e){
}
}
System.out.println("运行,i===>"+i);
}
}
static class MyThread implements Runnable{
private String name;
public MyThread(String name){
this.name = name;
}
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println(name+"运行,i="+i);
}
}
}
}
/**
线程的中断,实现Runnable接口
*/
class test3 {
public static void main(String[] args) {
MyThread m4 = new MyThread(); //实例化MyThread对象
Thread t1 = new Thread(m4); //实例化Thread对象
t1.start();//启动线程
try {
Thread.sleep(2000); //休眠2秒
}catch (InterruptedException e) {
System.out.println("休眠被终止");
}
t1.interrupt(); //中断线程执行 正常执行1,2,3,中断则执行1,4.
}
static class MyThread implements Runnable{
@Override
public void run() {
System.out.println("1,进入run方法");
try{
Thread.sleep(10000); //线程休眠10秒
System.out.println("2,休眠10秒");
}catch (InterruptedException e){
System.out.println("4,休眠被终止");
return; //返回调用处
}
System.out.println("3,退出run方法,结束");
}
}
}
/**
线程在后台运行,实现Runnable接口
*/
class test4 {
public static void main(String[] args) {
MyThread m1 = new MyThread(); //实例化MyThread对象
Thread t1 = new Thread(m1,"线程"); //实例化Thread对象
t1.setDaemon(true); //此线程在后台运行
t1.start(); //启动线程
}
static class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"在运行");
}
}
}
/**
线程的优先级,实现Runnable接口
*/
class test5 {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread(),"线程A"); //实例化Thread对象
Thread t2 = new Thread(new MyThread(),"线程B"); //实例化Thread对象
Thread t3 = new Thread(new MyThread(),"线程C"); //实例化Thread对象
t1.setPriority(Thread.MIN_PRIORITY); //优先级最低
t2.setPriority(Thread.MAX_PRIORITY); //优先级最高
t3.setPriority(Thread.NORM_PRIORITY); //优先级中等
t1.start(); //启动线程
t2.start();
t3.start();
}
static class MyThread implements Runnable{
@Override
public void run() {
for (int i=0;i<5;i++){
try {
Thread.sleep(500); //线程休眠
}catch (InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+"在运行,i==》"+i);
}
}
}
}
/**
同步锁(synchronized)
好处:可以保证多线程操作共享数据时的安全问题
弊端:降低了程序的执行效率。
*/
class test001 {
public static void main(String[] args){
Demo d = new Demo(); //创建线程任务
Thread t1 = new Thread(d); //创建线程对象
Thread t2 = new Thread(d);
Thread t3 = new Thread(d);
Thread t4 = new Thread(d);
t1.start(); //开启线程
t2.start();
t3.start();
t4.start();
}
static class Demo implements Runnable{
int num = 100; //定义变量记录剩余的票数
Object obj = new Object(); //创建一个对象,用作同步中的锁对象
public void run(){ //实现run方法
while(true){ //实现售票的过程 t1 t2 t3
synchronized( obj ){ //t1 在进入同步之前线程要先获取锁,当某个线程执行到synchronized关键字之后,这时JVM会判断当前同步上的这个对象有没有已经被其他线程获取走了,如果这时没有其他线程获取这个对象,这时就会把当前同步上的这个对象交给当前正要进入同步的这个线程。
if( num > 0 ) { //判断当前有没有线程正在if中操作num,如果有当前线程就在这里临时等待这种思想称为线程的同步,当票数小等于0的时候,就不再售票了,使用同步代码块把线程要执行的任务代码可以同步起来
try{Thread.sleep(2);}catch( InterruptedException e ){}
System.out.println(Thread.currentThread().getName()+"=====>"+num);
num--;
}
}//线程执行完同步之后,那么这时当前这个线程就会把锁释放掉
}
}
}
}
//多人抢票可能导致错误数据出现,造成错误数据的原因是多个线程可能出现同时访问num的情况。
// 而任何一个线程在访问num的过程中都可以切换到其他的线程上。而其他线程一旦把num的数据改变了,
// 再切换回来时,错误数据就有了。
public void run(){
//售票10张
int num = 10;
//春节开始抢票了
while(true){
//当票小于0停止抢票
if(num>0)
System.out.println("疯狂加速抢票中!");
System.out.println(Thread.currentThread().getName()+num);
num--;
}
}
·····X1·····
·····X0·····
package tests.demo.reconnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class HttpGET implements Runnable{
public static String txtUrl="";
@Override
public void run() {
while (true) {
try {
Thread.sleep(2000);
String s = httpGet(txtUrl);
System.out.println(s);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public String httpGet(String url) {
txtUrl=url;
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("contentType", "utf8");
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));//防止乱码
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
result = "";
}
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
HttpGET target = new HttpGET();
target.httpGet("http://www.weather.com.cn/data/cityinfo/101281601.html");
new Thread(target).start();
}
}
·····X1·····
···················································································································································································
one hundred and twelve Java Environment setting instance(环境设置)
如何执行编译过 Java 文件
如何执行编译过的 HelloWorld.java 文件,其中 Java 代码如下:
public class HelloWorld {
public static void main(String []args) {
System.out.println("Hello World");
}
}
linux
jdk根目录/bin/java -jar xx.jar
Windows
jdk根目录/bin/java -jar xx.jar
c:\jdk\demoapp> javac HelloWorld.java
c:\jdk\demoapp> java HelloWorld
如何执行指定class文件目录(classpath)
如果我们 Java 编译后的class文件不在当前目录,我们可以使用 -classpath 来指定class文件目录:
C:> java -classpath C:\java\DemoClasses HelloWorld
以上命令中我们使用了 -classpath 参数指定了 HelloWorld 的 class 文件所在目录。
如果class文件在jar文件中,则命令如下:
c:> java -classpath C:\java\myclasses.jar
如何查看当前 Java 运行的版本?
java -version
如何查看当前 Java 安装的路径?
java -verbose
···················································································································································································
one hundred and thirteen log(日志)
·····X0·····
package com.lct.web_service.log;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class Logs {
public static final Logger logger = Logger.getGlobal();
public Logs(){
StringBuffer logPath=new StringBuffer();
String curDir = System.getProperty("user.dir"); //当前的工作目录
File logs = new File(curDir+"\\logs");
if(!logs.exists()){ // 如果当前目录下没有logs文件夹,则创建这个文件夹
logs.mkdir();
}
logPath.append(curDir+"\\logs"); //设置保存路径
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
logPath.append("\\"+sdf.format(new Date())+".log"); //设置文件名
week(); //(清理一周日志)
//将输出handler加入logger
try {
FileHandler fileHandler=new FileHandler(logPath.toString(),true);
logger.addHandler(fileHandler);
}catch (IOException e){
e.printStackTrace();
}
}
public static void week(){
Long timeStamp = System.currentTimeMillis(); //获取当前时间戳
Long week = timeStamp-(7 * 24 * 60 * 60 * 1000); //天 时 分 秒 毫秒 (一周)
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String sd = sdf.format(new Date(Long.parseLong(String.valueOf(week)))); // 时间戳转换成时间
String log = sd + ".log";
String userDir = System.getProperty("user.dir"); //当前的工作目录
try{
File file = new File(userDir+"\\logs\\"+ log);
if(file.delete()){
System.out.println("文件详细路径:" + file + "\n" + file.getName() + " 文件已被删除!");
}else{
System.out.println("文件详细路径:" + file + "\n" + file.getName() + " 文件不存在或已删除!");
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
//日志记录器
Logs log = new Logs();
log.logger.info("\n 日志记录器:" + "xxxx年xx月xx日xx:xx:xx \n");
week();
}
}
·····X1·····
···················································································································································································
one hundred and fourteen timed task(timer)(定时器)
·····X0·····
package com.lct.web_service.log;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
/*
//日志记录器
// Logs log = new Logs();
// log.logger.info("\n 日志记录器:" + "xxxx年xx月xx日xx:xx:xx \n");
*/
public class Logs {
public static final Logger logger = Logger.getGlobal();
public Logs(){
StringBuffer logPath=new StringBuffer();
String curDir = System.getProperty("user.dir"); //当前的工作目录
File logs = new File(curDir+"\\logs");
if(!logs.exists()){ // 如果当前目录下没有logs文件夹,则创建这个文件夹
logs.mkdir();
}
logPath.append(curDir+"\\logs"); //设置保存路径
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
logPath.append("\\"+sdf.format(new Date())+".log"); //设置文件名
timerTask();
//将输出handler加入logger
try {
FileHandler fileHandler=new FileHandler(logPath.toString(),true);
logger.addHandler(fileHandler);
}catch (IOException e){
e.printStackTrace();
}
}
/**
* 清理一周日志
*/
public static void week(){
Long timeStamp = System.currentTimeMillis(); //获取当前时间戳
Long week = timeStamp-(7 * 24 * 60 * 60 * 1000); //天 时 分 秒 毫秒 (一周)
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String sd = sdf.format(new Date(Long.parseLong(String.valueOf(week)))); // 时间戳转换成时间
String log = sd + ".log";
String userDir = System.getProperty("user.dir"); //当前的工作目录
try{
File file = new File(userDir+"\\logs\\"+ log);
if(file.delete()){
System.out.println("文件详细路径:" + file + "\n" + file.getName() + " 文件已被删除!");
}else{
System.out.println("文件详细路径:" + file + "\n" + file.getName() + " 文件不存在或已删除!");
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 定时清理日志 (每天清理一次)
*/
public static void timerTask(){
// 定义一个任务
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
week(); // 每天清理一次日志
System.out.println("打印当前时间:" + new Date());
}
};
// 计时器
Timer timer = new Timer();
// 开始执行任务 (延迟1000毫秒 执行,每3000毫秒 执行一次)
// timer.schedule(timerTask, 1000, 3000);
// 开始执行任务 (延迟1000毫秒 执行,每天 执行一次)
timer.schedule(timerTask, 1000, 24 * 60 * 60 * 1000);
}
public static void main(String[] args) {
timerTask();
}
}
·····X1·····
···················································································································································································
one hundred and fifteen export(导出)
·····X0·····
package com.example.newspringboot.excel;
import lombok.Data;
import java.io.Serializable;
@Data
public class District implements Serializable {
private String name;
private String code;
private String hobby;
}
package com.example.newspringboot.excel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
@Slf4j
public class MyCsvFileUtil {
public static final String FILE_SUFFIX = ".csv";
public static final String CSV_DELIMITER = ",";
public static final String CSV_TAIL = "\r\n";
protected static final String DATE_STR_FILE_NAME = "yyyyMMddHHmmssSSS";
/**
* 将字符串转成csv文件
*/
public static void createCsvFile(String savePath, String contextStr) throws IOException {
File file = new File(savePath);
//创建文件
file.createNewFile();
//创建文件输出流
FileOutputStream fileOutputStream = new FileOutputStream(file);
//将指定字节写入此文件输出流
fileOutputStream.write(contextStr.getBytes("gbk"));
fileOutputStream.flush();
fileOutputStream.close();
}
/**
* 写文件
*
* @param fileName
* @param content
*/
public static void writeFile(String fileName, String content) {
FileOutputStream fos = null;
OutputStreamWriter writer = null;
try {
fos = new FileOutputStream(fileName, true);
writer = new OutputStreamWriter(fos, "GBK");
writer.write(content);
writer.flush();
} catch (Exception e) {
log.error("写文件异常|{}", e);
} finally {
if (fos != null) {
IOUtils.closeQuietly(fos);
}
if (writer != null) {
IOUtils.closeQuietly(writer);
}
}
}
/**
* 构建文件名称
* @param dataList
* @return
*/
public static String buildCsvFileFileName(List dataList) {
return dataList.get(0).getClass().getSimpleName() + new SimpleDateFormat(DATE_STR_FILE_NAME).format(new Date()) + FILE_SUFFIX;
}
/**
* 构建excel 标题行名
* @param dataList
* @return
*/
public static String buildCsvFileTableNames(List dataList) {
Map<String, Object> map = toMap(dataList.get(0));
StringBuilder tableNames = new StringBuilder();
for (String key : map.keySet()) {
tableNames.append(key).append(MyCsvFileUtil.CSV_DELIMITER);
}
return tableNames.append(MyCsvFileUtil.CSV_TAIL).toString();
}
/**
* 构建excel内容
* @param dataLists
* @return
*/
public static String buildCsvFileBodyMap(List dataLists) {
//不管你传什么玩意,我都给你反射一手,搞成Map
List<Map<String, Object>> mapList = new ArrayList<>();
for (Object o : dataLists) {
mapList.add(toMap(o));
}
//然后利用csv格式,对着map嘎嘎一顿拼接数据
StringBuilder lineBuilder = new StringBuilder();
for (Map<String, Object> rowData : mapList) {
for (String key : rowData.keySet()) {
Object value = rowData.get(key);
if (Objects.nonNull(value)) {
lineBuilder.append(value).append(MyCsvFileUtil.CSV_DELIMITER);
} else {
lineBuilder.append("--").append(MyCsvFileUtil.CSV_DELIMITER);
}
}
lineBuilder.append(MyCsvFileUtil.CSV_TAIL);
}
return lineBuilder.toString();
}
/**
* 类转map
* @param entity
* @param <T>
* @return
*/
public static<T> Map<String, Object> toMap(T entity){
Class<? extends Object> bean = entity.getClass();
Field[] fields = bean.getDeclaredFields();
Map<String, Object> map = new HashMap<>(fields.length);
for(Field field:fields){
try {
if(!"serialVersionUID".equals(field.getName())){
String methodName = "get"+field.getName().substring(0, 1).toUpperCase()+field.getName().substring(1);
Method method = bean.getDeclaredMethod(methodName);
Object fieldValue = method.invoke(entity);
map.put(field.getName(),fieldValue);
}
} catch (Exception e) {
log.warn("toMap() Exception={}",e.getMessage());
}
}
return map;
}
}
package com.example.newspringboot.excel;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* 依赖包
* <dependency>
* <groupId>org.apache.poi</groupId>
* <artifactId>poi-ooxml</artifactId>
* <version>3.15</version>
* </dependency>
* <dependency>
* <groupId>org.apache.poi</groupId>
* <artifactId>poi-scratchpad</artifactId>
* <version>3.15</version>
* </dependency>
* <dependency>
* <groupId>com.alibaba</groupId>
* <artifactId>fastjson</artifactId>
* <version>1.2.69</version>
* </dependency>
* <dependency>
* <groupId>commons-io</groupId>
* <artifactId>commons-io</artifactId>
* <version>2.5</version>
* </dependency>
*/
public class Main {
public static void main(String[] args) {
List<District> districts = new ArrayList<>();
District district1 = new District();
District district2 = new District();
District district3 = new District();
district1.setCode("d1Code");
district1.setHobby("d1Hobby");
district1.setName("d1Name");
district2.setCode("d2Code");
district2.setHobby("d2Hobby");
district2.setName("d2Name");
district3.setCode("d3Code");
district3.setHobby("d3Hobby");
district3.setName("d3Name");
districts.add(district1);
districts.add(district2);
districts.add(district3);
String fileName = url() + MyCsvFileUtil.buildCsvFileFileName(districts); //当前工作目录
// 创建表格行标题
String tableNames = MyCsvFileUtil.buildCsvFileTableNames(districts);
// 创建文件
MyCsvFileUtil.writeFile(fileName, tableNames);
// 写入数据
String contentBody = MyCsvFileUtil.buildCsvFileBodyMap(districts);
// 调用方法生成
MyCsvFileUtil.writeFile(fileName, contentBody);
}
/**
* @return 当前工作目录 mycsv文件
*/
public static String url(){
StringBuffer logPath=new StringBuffer();
String curDir = System.getProperty("user.dir"); //当前的工作目录
File logs = new File(curDir+"\\mycsv\\");
if(!logs.exists()){ // 如果当前目录下没有logs文件夹,则创建这个文件夹
logs.mkdir();
}
return curDir+"\\mycsv\\";
}
}
·····X1·····
···················································································································································································
one hundred and sixteen network gateway(网络网关)
·····X0·····
如果没有配置DNS,则不用配置,如果配置了DNS,则配置
·····X1·····
···················································································································································································
one hundred and seventeen Java ehcache(cache)(缓存)
·····X0·····
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>
目录:resources/ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- helloworld缓存 -->
<cache name="HelloWorldCache"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="604800"
timeToLiveSeconds="604800"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
//测试
package util;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class Test {
// 1. 创建缓存管理器
public static CacheManager cacheManager = CacheManager.create("./src/main/resources/ehcache.xml");
public static void main(String[] args) {
// 2. 获取缓存对象
Cache cache = Test.cacheManager.getCache("HelloWorldCache");
// 3. 创建元素
Element element = new Element("key1", "1231231");
// 4. 将元素添加到缓存
cache.put(element);
// 5. 获取缓存
Element value = cache.get("key1");
System.out.println("value: " + value);
System.out.println(value.getObjectValue());
}
}
·····X1·····
···················································································································································································
one hundred and eighteen Linux,Windows,MacOS System judgment(操作系统)
·····X0·····
package util;
public class SystemUtils {
/**
* 判断操作系统是否是 Windows
*
* @return true:操作系统是 Windows
* false:其它操作系统
*/
public static boolean isWindows() {
String osName = getOsName();
return osName != null && osName.startsWith("Windows");
}
/**
* 判断操作系统是否是 MacOS
*
* @return true:操作系统是 MacOS
* false:其它操作系统
*/
public static boolean isMacOs() {
String osName = getOsName();
return osName != null && osName.startsWith("Mac");
}
/**
* 判断操作系统是否是 Linux
*
* @return true:操作系统是 Linux
* false:其它操作系统
*/
public static boolean isLinux() {
String osName = getOsName();
return (osName != null && osName.startsWith("Linux")) || (!isWindows() && !isMacOs());
}
/**
* 获取操作系统名称
* @return os.name 属性值
*/
public static String getOsName() {
return System.getProperty("os.name");
}
public static void main(String[] args) {
System.out.println(SystemUtils.getOsName());
System.out.println(SystemUtils.isLinux());
System.out.println(SystemUtils.isWindows());
System.out.println(SystemUtils.isMacOs());
}
}
·····X1·····
···················································································································································································
one hundred and nineteen DB
·····X0·····
依赖包
sqlite-jdbc-3.20.1
package main;
import java.io.File;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DbClass {
private static Connection connection;
private static Statement statement;
public static String allTables = "";
public DbClass(){
try {
String property = System.getProperty("user.dir");
System.out.println("当前目录: \n" + property);
if(!new File(property + File.separator + "dbs2" ).exists()) {
new File(property + File.separator + "dbs2").mkdir();
System.out.println("创建dbs2文件夹");
}
if(!new File(property + File.separator + "dbs2" + File.separator + "db").exists()) {
new File(property + File.separator + "dbs2" + File.separator + "db").mkdir();
System.out.println("创建db文件夹");
}
connection = DriverManager.getConnection("jdbc:sqlite:dbs2/db/xwf.db");
statement = connection.createStatement();
getTables();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 所有表
*/
private static void getTables() {
try {
DatabaseMetaData dbMetData = connection.getMetaData();
// mysql convertDatabaseCharsetType null
ResultSet rs = dbMetData.getTables(null,null,"%",null);
while (rs.next()) {
if (rs.getString(4) != null
&& (rs.getString(4).equalsIgnoreCase("TABLE") || rs
.getString(4).equalsIgnoreCase("VIEW"))) {
String tableName = rs.getString(3).toLowerCase();
allTables=allTables+tableName+",";
System.out.print(tableName + "\n");
// 根据表名提前表里面信息:
ResultSet colRet = dbMetData.getColumns(null, "%", tableName, "%");
while (colRet.next()) {
String columnName = colRet.getString("COLUMN_NAME");
String columnType = colRet.getString("TYPE_NAME");
int datasize = colRet.getInt("COLUMN_SIZE");
int digits = colRet.getInt("DECIMAL_DIGITS");
int nullable = colRet.getInt("NULLABLE");
System.out.println(columnName + " " + columnType + " "+ datasize + " " + digits + " " + nullable);
}
}
}
System.out.println();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 建表
*/
public static void createTable(String tableName,String sql){
try {
//建表
if(!allTables.contains(tableName)){
System.out.println(tableName+"表创建成功!");
statement.executeUpdate(sql);
}else {
System.out.println(tableName+"创建失败,表已存在!");
}
statement.close();
} catch (Exception s) {
s.printStackTrace();
}
}
/**
*
* @param sql 增加,修改,删除 (不能查询)
*/
public static void insert_update_delete (String sql){
try{
statement.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 查询
* @param sql (select * from sqlite_master)
*/
public static void OriginalData(String sql){
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1.获取数据库的连接 2.获取PreparedStatement的实例 (或:预编译sql语句)
ps = connection.prepareStatement(sql);// select * from sqlite_sequence //historydata //sqlite_master //sqlite_sequence
//3.执行sql语句
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
System.out.println("\n"+"rsmd: "+rsmd+"\n"+"columnCount: "+columnCount);
// 将数据封装为Map
List<Map<String, Object>> list = new ArrayList<>();
while (rs.next()) {
Map<String, Object> columnMap = new HashMap<>();
// 注:列名的索引 起始是 1 不是 0
for (int i = 1; i <= columnCount; i++) {
System.out.println("getColumnName(i)获取该列的原始名字: " + rsmd.getColumnName(i));
System.out.println("getColumnLabel(i)获取该列的别名: " + rsmd.getColumnLabel(i));
System.out.println("getColumnClassName(i)获取该列的(在java中的)数据类型: " + rsmd.getColumnClassName(i));
System.out.println("getColumnType(i)获取该列的(在数据库中的)数据类型对应的序号: " + rsmd.getColumnType(i));
System.out.println("getColumnTypeName(i)获取该列的(在数据库中的)数据类型: " + rsmd.getColumnTypeName(i));
System.out.println("getScale(i)获取该列中小数点右边的位数: " + rsmd.getScale(i));
System.out.println("isNullable(i)获取该列的长度: " + rsmd.isNullable(i));
System.out.println("isAutoIncrement(i)判断该列的值是否自动递增: " + rsmd.isAutoIncrement(i));
System.out.println("isNullable(i)判断该列的值是否为null: " + rsmd.isNullable(i));
System.out.println("getTableName(i)获取表名: " + rsmd.getTableName(i));
System.out.println();
String key = rsmd.getColumnName(i);
Object value = rs.getObject(key);
columnMap.put(key, value);
}
list.add(columnMap);
}
System.out.println(list);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DbClass(); //首先必须初始化。
//mes_user为表名,MyIndex 为自增,hobby可以为空,username不能为空,password不能为空。
createTable("mes_user",
"create table `mes_user` "+
"(`MyIndex` integer primary key autoincrement," +
"hobby varchar(50) default null,"
+"username varchar(50) not null,"
+ "password varchar(20) not null ); ");
//增加 注意'\" '\"
insert_update_delete("insert into mes_user (username,password) values ('\"张三\"','\"123456\"')");
insert_update_delete("insert into mes_user (username,password) values ('\"李四\"','\"123456\"')");
//查询 该表所有数据
OriginalData("select * from mes_user");
//修改 注意'\" '\" 要保持一致
insert_update_delete("UPDATE mes_user SET password = '\"234567\"' WHERE username = '\"李四\"'");
//查询 该表所有数据
OriginalData("select * from mes_user");
//删除 注意'\" '\" 要保持一致
insert_update_delete("DELETE FROM mes_user WHERE username = '\"李四\"'");
//查询 该表所有数据
OriginalData("select * from mes_user");
}
}
·····X1·····
···················································································································································································
one hundred and twenty sql
·····X0·····
清空数据库表内容
truncate table cloud_company
truncate table cloudp00
truncate table cloud_role
truncate table cloud_rights
truncate table cloud_cuser
查询当前数据库所有表
SELECT table_name, table_comment, create_time, update_time
FROM information_schema.tables
WHERE table_schema = (SELECT DATABASE())
ORDER BY create_time DESC
查询
SELECT 列名称 FROM 表名称 WHERE 列 运算符 值
SELECT LastName,FirstName FROM 表名称
添加
INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
修改
UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
UPDATE student SET sname = '张三' WHERE sid = 1
删除
DELETE FROM 表名称 WHERE 列名称 = 值
DELETE FROM 表student WHERE id = 1
使用 AND 来显示所有姓为 "Carter" 并且名为 "Thomas" 的人:
SELECT * FROM Persons WHERE FirstName='Thomas' AND LastName='Carter'
使用 OR 来显示所有姓为 "Carter" 或者名为 "Thomas" 的人:
SELECT * FROM Persons WHERE firstname='Thomas' OR lastname='Carter'
排序ORDER BY
SELECT 列名称1, 列名称2 FROM 表名称 ORDER BY 列名称1
SELECT Company, OrderNumber FROM Orders ORDER BY Company
去重
application_name(列) alibaba_developer(表)
SELECT DISTINCT 列名称 FROM 表名称
SELECT DISTINCT application_name FROM alibaba_developer
求和
功能:加法运算。加数为:年龄,条件名字为:张三
SELECT SUM(列名称) FROM 表名称 where name= '张三'
SELECT SUM(age) FROM user where name= '张三'
求行数
功能:数行数。 条件名字为:张三
SELECT COUNT(*) FROM 表名称 where name= '张三'
SELECT COUNT(*) FROM user where name= '张三'
日期:功能:数行数。 条件时间为:今天 默认格式,列名称为:user_date
SELECT COUNT(*) FROM user where DateDiff(dd,user_date,getdate())=0
日期:功能:数行数。 条件时间为:这个月 默认格式,列名称为:user_date
select COUNT(*) from eshop_Po where datediff(Month,user_date,getdate())=0
添加
insert into command_status(machine_id,msg_date_time) values('ms1','2023-08-17 10:00:00.000');
修改
UPDATE command_status SET msg_date_time = '2022-02-22 10:00:00.000' WHERE machine_id = 'ms1';
删除
DELETE FROM command_status WHERE machine_id = 'ms1';
给原表新增加一列
mplc215_sub表,新增一列。processAlignOffsetXY(process_align_offset_xy)。
ALTER TABLE mplc215_sub ADD COLUMN process_align_offset_xy varchar(255) DEFAULT NULL ;
从 JDBC 类型映射到 Java 类型
JDBC 类型 | Java 类型 |
---|---|
CHAR | String |
VARCHAR | String |
LONGVARCHAR | String |
NUMERIC | java.math.BigDecimal |
DECIMAL | java.math.BigDecimal |
BIT | boolean |
TINYINT | byte |
SMALLINT | short |
INTEGER | int |
BIGINT | long |
REAL | float |
FLOAT | double |
DOUBLE | double |
BINARY | byte[] |
VARBINARY | byte[] |
LONGVARBINARY | byte[] |
DATE | java.sql.Date |
TIME | java.sql.Time |
TIMESTAMP | java.sql.Timestamp |
text | String |
DateTime | Date |
UInt8类型在数据库中通常对应着TINYINT类型。
·····X1·····
···················································································································································································
one hundred and twenty-one Entity class attribute sorting(实体类属性排序)
·····X0·····
实体类属性排序 从a到z
public static void main(String[] args) {
// 创建实体类对象
YourEntityClass entity = new YourEntityClass();
// 获取所有属性
Field[] fields = entity.getClass().getDeclaredFields();
// 将属性存储到列表中
List<String> propertyList = new ArrayList<>();
for (Field field : fields) {
propertyList.add(field.getName());
}
// 对属性列表按字母顺序进行排序
Collections.sort(propertyList, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
// 打印排序后的属性列表
for (String property : propertyList) {
System.out.println(property);
}
}
·····X1·····
···················································································································································································
one hundred and twenty-two Hexadecimal to a character string(十六进制字符串)
·····X0·····
class test90{
public static void main(String[] args) {
String str ="3c:3f:78:6d:6c:20:76:65:72:73:69:6f:6e:3d:22:31";
str = str.replaceAll(":"," ");
System.out.println(str);
String s = hexStringToString(str);
System.out.println(s);
}
/**
* 16进制转换成为string类型字符串
* @param s
* @return
*/
public static String hexStringToString(String s) {
if (s == null || s.equals("")) {
return null;
}
s = s.replace(" ", "");
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "UTF-8");
new String();
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}
}
·····X1·····
···················································································································································································
one hundred and twenty-three Hexadecimal to a character string(idea编码,快捷键…)
·····X0·····
1
idea的bin目录里面的idea.exe.vmoptions 和 idea64.exe.vmoptions文件,末尾添加-Dfile.encoding=UTF-8
2
idea设置,settings → Editor → file Encodings 全都修改为UTF-8
3
设置VM options为-Dfile.encoding=UTF-8
4
打开Help → Edit Custom VM Options... 在末尾添加-Dfile.encoding=UTF-8
5
在.idea的文件夹里面有个encodings.xml 的文件,除了UTF-8 的都删了
删除前
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" native2AsciiForPropertiesFiles="true" defaultCharsetForPropertiesFiles="GBK">
<file url="file://$PROJECT_DIR$/mesAgentConfig/webSet.pro" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java/mesAgent/customerClient/http/util/SECExecptionHandler.java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
删除后
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" defaultCharsetForPropertiesFiles="UTF-8" addBOMForNewFiles="with BOM">
<file url="PROJECT" charset="UTF-8" />
</component>
</project>
·····X1·····
···················································································································································································
SocketClient(持续连接)
·····X0·····
dy
package company.AAAsocket;
import util.FileMethod;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Date;
public class HttpSocket extends Thread{
public String address = "127.0.0.1";
public int port = 8026;
public Socket socket1;
public static boolean bRun = true;
public BufferedReader in;
public Reader reader;
private String strSocketNew = "";
public PrintStream outStream;
public Writer outStream2;
public static void main(String[] args) {
HttpSocket httpSocket = new HttpSocket(); //将此放入主类,调用如下
httpSocket.start();
httpSocket.send("你好");
httpSocket.send2("你好2");
}
HttpSocket(){
init();
}
public void init() {
while (true) {
if (socket1 != null && socket1.isConnected() && !socket1.isClosed()) {
bRun = true;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket1.getInputStream(), StandardCharsets.UTF_16)); //接收方式1
reader = new InputStreamReader(socket1.getInputStream(), "utf-8");//接收方式2
} catch (Exception ie) {
}
while (bRun) {
try {
receive();
} catch (Exception ie) {
ie.printStackTrace();
}
}
} else {
try {
socket1 = new Socket(address,port);
// socket1 = new Socket(StyleProperties.mainFrame.HttpClientSocketIP, StyleProperties.mainFrame.HttpClientSocketPort);
System.out.println("\n连接成功\n");
outStream = new PrintStream(socket1.getOutputStream(),true, "gbk");
outStream2 = new OutputStreamWriter(socket1.getOutputStream());
} catch (IOException io) {
if (!strSocketNew.equalsIgnoreCase(io.getMessage())) {
strSocketNew = io.getMessage();
}
}
}
}
}
public void receive() {
try {
try {
Thread.sleep(5000);
socket1.sendUrgentData(0xFF);
} catch (Exception e) {
e.printStackTrace();
socket1 = null;
bRun = false;
}
char chars[] = new char[64];
int len;
StringBuilder sb = new StringBuilder();
String temp;
int index;
String strJson = "";
while ((len = reader.read(chars)) != -1) {
temp = new String(chars, 0, len);
// if ((index = temp.indexOf("}")) != -1) { //遇到eof时就结束接收
// sb.append(temp.substring(0, index));
// break;
// }
sb.append(temp);
if(sb.toString().contains("{") && sb.toString().contains("}") && strcou(sb.toString(), "{" ) == strcou(sb.toString(), "}")){
String str = sb.toString().substring(sb.toString().indexOf("{"),sb.toString().lastIndexOf("}")+1);
break;
}
}
String requestString = sb.toString();
System.out.println("请求消息:" + requestString);
//处理数据
int begin = requestString.indexOf("<messagename>");
int end = requestString.indexOf("</messagename>");
// String messagename = requestString.substring(begin+"<messagename>".length() ,end);
String messagename = "";
FileMethod.machine((new Date() + "eekp_receive---> " + messagename)); //接收
if (messagename.equals("AreYouThereRequest")) {
// String str = EekpMesReply.mesAreYouThereRequestReply(); //回复
// StyleProperties.mainFrame.httpClientSocket.send(str);
}
//4.6Remote Control Command 弹窗
if (messagename.equals("RemoteControlCommand")) {
// String str = EekpMesReply.mesRemoteControlCommandReply();
// StyleProperties.mainFrame.httpClientSocket.send(str);
// Dialog dialog = new Dialog();
// Thread.sleep(5000);
// dialog.setVisible(false);
}
//4.5CIM Message Command 弹窗
if (messagename.equals("CIMMessageCommand")) {
String substr = substr("<interval_second_time>", "</interval_second_time>", requestString);
// cim_message= StringUtil.substr("<cim_message>", "</cim_message>", requestString);
System.out.println("时间:"+substr);
}
//4.2Initial Data Request 初始化数据
if (messagename.equals("InitialDataRequest")) {
// String str = EekpMesReply.mesInitialDataReply();
// StyleProperties.mainFrame.httpClientSocket.send(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//发送方式1
public void send(String StringIn) {
outStream.println(StringIn);
}
//发送方式2
public void send2(String StringIn) {
try {
outStream2.write(StringIn);
outStream2.flush();
}catch (Exception e){
e.printStackTrace();
}
}
public static String substr(String begin,String end,String data){
if(data.contains(begin)){
int beginOf=data.indexOf(begin);
int endOf=data.indexOf(end);
String str = data.substring(beginOf+begin.length() ,endOf);
return str;
}else {
return null;
}
}
/**
* 出现的次数
*/
public static int strcou(String data,String subStr){
int count = 0;
int i = 0;
while (true) {
if (data.indexOf(subStr, i) == -1) {
break;
} else {
count++;
i = data.indexOf(subStr, i) + 1;
}
}
return count;
}
}
eekp
package mesAgent.customerClient.http;
import mesAgent.customerClient.http.util.FileMethod;
import mesAgent.customerClient.http.util.StringUtil;
import mesAgent.entrance.MainFrame;
import mesAgent.template.operation.Machine;
import mesAgent.template.operation.Recipe;
import mesAgent.template.operation.StyleProperties;
import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
import java.net.Socket;
public class HttpClientSocket extends Thread {
private static int mes_num = 0;
public static final transient SimpleDateFormat tsFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
MainFrame mainFrame;
private static final Logger logger = Logger.getLogger(HttpClientSocket.class);
public static boolean bRun = true;
private boolean machineFlag = true;
public static boolean httpClientbRun = true;
public Socket socket1;
// public PrintStream outStream;
public OutputStream outStream;
// public OutputStream ops;
public BufferedReader in;
public InputStream input;
public String address = "127.0.0.1";
public int port = 8089;
private String strSocketNew = "";
public String strFromMes = "";
// public static String EEKPrecipe_path;
public static String ModeMsg;
public static String cim_message;
public static Object return_result;
public static String job_id;
public static String process_id;
public static String recipe_path;
public static String cam_path;
@Override
public void run() {
while (true) {
if (socket1 != null && socket1.isConnected() && !socket1.isClosed()) {
bRun = true;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
input = socket1.getInputStream();
in = new BufferedReader(new InputStreamReader(input,StandardCharsets.UTF_16));
} catch (Exception ie) {
}
while (bRun) {
try {
receive();
} catch (Exception ie) {
ie.printStackTrace();
}
}
} else {
try {
// socket1 = new Socket(address,port);
socket1 = new Socket(StyleProperties.mainFrame.HttpClientSocketIP, StyleProperties.mainFrame.HttpClientSocketPort);
System.out.println("HttpClientSocket->" + StyleProperties.mainFrame.HttpClientSocketIP + ":" + StyleProperties.mainFrame.HttpClientSocketPort);
System.out.println("\nHttpClientSocket , lianJieChengGong\n");
print(10);
outStream = socket1.getOutputStream();
// ops= socket1.getOutputStream();
} catch (IOException io) {
if (!strSocketNew.equalsIgnoreCase(io.getMessage())) {
strSocketNew = io.getMessage();
}
}
}
}
}
char head = 0x2;
char tail = 0x3;
//接收
public void receive() throws IOException {
try {
try {
Thread.sleep(5000);
socket1.sendUrgentData(0xFF);
} catch (Exception e) {
e.printStackTrace();
socket1 = null;
bRun = false;
}
strFromMes = "";
String line;
int b;
StringBuilder requestData = new StringBuilder();
while ((line = in.readLine()) != null) {
// System.out.println(b);
// if ((char)b == head) {
// continue;
// }
requestData.append(line);
// strFromMes += line + "\n";
// line = line.replaceAll("\u0000", "").replaceAll("\u0002", "");
// strFromMes = strFromMes.replaceAll("\u0000", "").replaceAll("\u0002", "");
// System.out.println((char)b);
if(line.contains("</message>")){
break;
}
}
// String requestString = requestData.replace(0,2,"<").toString();
String requestString = requestData.toString();
System.out.println("请求消息:" + requestString);
// Map<String, Object> objectMap = JsonAndXmlConvertor.xmlToJsonObject(requestString);
// System.out.println(objectMap);
int begin=requestString.indexOf("<messagename>");
int end=requestString.indexOf("</messagename>");
String messagename = requestString.substring(begin+"<messagename>".length() ,end);
logger.info("eekp receive] -> " +messagename);
FileMethod.machine((new Date() + "eekp_receive---> " + messagename)); //接收
if (messagename.equals("AreYouThereRequest")) {
String str = EekpMesReply.mesAreYouThereRequestReply(); //回复
StyleProperties.mainFrame.httpClientSocket.send(str);
}
//4.7Job Data Download
if (messagename.equals("JobDataDownload")) {
process_id =StringUtil.substr("<recipe_name>","</recipe_name>",requestString);
System.out.println("process_id:--->"+process_id);
recipe_path = StringUtil.substr("<recipe_path>","</recipe_path>",requestString);
// Recipe.camName = StringUtil.substr("<cam_name>","</cam_name>",requestString);
cam_path = StringUtil.substr("<cam_path>","</cam_path>",requestString);
String port_id = StringUtil.substr("<port_id>","</port_id>",requestString);
job_id = StringUtil.substr("<job_id>","</job_id>",requestString);
String total_panel_count = StringUtil.substr("<total_panel_count>","</total_panel_count>",requestString);
String str = EekpMesReply.mesJobDataDownloadReply();
StyleProperties.mainFrame.httpClientSocket.send(str);
StyleProperties.machine.LotCode.setText(port_id);
StyleProperties.machine.ProductCode.setText(job_id);
StyleProperties.machine.PnlQty.setText(total_panel_count);
String list=StringUtil.substr("<recipe_parameter_list>","</recipe_parameter_list>",requestString);
// Recipe.SECsetMesText(list); //job data 展示配方
Recipe.recipe_cutName(list); // 更改为具体路径
}
//4.6Remote Control Command 弹窗
if (messagename.equals("RemoteControlCommand")) {
String str = EekpMesReply.mesRemoteControlCommandReply();
StyleProperties.mainFrame.httpClientSocket.send(str);
Dialog dialog = new Dialog();
Thread.sleep(5000);
dialog.setVisible(false);
}
//4.5CIM Message Command 弹窗
if (messagename.equals("CIMMessageCommand")) {
String substr = StringUtil.substr("<interval_second_time>", "</interval_second_time>", requestString);
cim_message= StringUtil.substr("<cim_message>", "</cim_message>", requestString);
System.out.println("时间:"+substr);
if(substr.equals("0")){
String str = EekpMesReply.mesCIMMessageCommandReply();
StyleProperties.mainFrame.httpClientSocket.send(str);
new Dialog();
String ts = tsFormat.format(new Date());
mes_num += 1;
String mes = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<schmoll_mes_message version=\"1\">\n" +
" <cmd_type>Write</cmd_type>\n" +
" <cmd_id>common.OperatorMessages</cmd_id>\n" +
" <cmd_variant>" + mes_num + "</cmd_variant>\n" +
" <msg_id>" + mes_num + "</msg_id>\n" +
" <msg_result>0</msg_result>\n" +
" <sender_id>MES Servername</sender_id>\n" +
" <receiver_id>Machine #10124</receiver_id>\n" +
" <msg_timestamp>" + ts.substring(0, 26) + ":" + ts.substring(26) + "</msg_timestamp>\n" +
" <data_timestamp>" + ts.substring(0, 26) + ":" + ts.substring(26) + "</data_timestamp>\n" +
" <data>\n" +
" <text>蜂鸣器</text>\n" +
" </data>\n" +
"</schmoll_mes_message>";
mes = "SMDATMSG,1,schmoll_mes_message,application/xml,"+mes.length()+"\n" +
mes + "\nSMDATEND";
mainFrame.schmollClientImpl.send(mes);
}else {
String str = EekpMesReply.mesCIMMessageCommandReply();
StyleProperties.mainFrame.httpClientSocket.send(str);
Dialog dialog = new Dialog();
Long aLong = Long.valueOf(substr);
Thread.sleep(aLong *1000);
dialog.setVisible(false);
}
}
//4.4Control Mode Command //远程控制模式 1离线本地 2在线远程
if (messagename.equals("ControlModeCommand")) {
int beginp=requestString.indexOf("<control_mode>");
int endp=requestString.indexOf("</control_mode>");
ModeMsg = requestString.substring(beginp+"<control_mode>".length() ,endp);
String str = EekpMesReply.mesControlModeCommandReply();
StyleProperties.mainFrame.httpClientSocket.send(str);
String schmollMode;
if(ModeMsg.equals("1")){
schmollMode="Offline"; //离线
Machine.toggleBtn.setText("CIM OFF");
for (JButton jButton:StyleProperties.limitList){
jButton.setEnabled(true);
System.out.println("离线激活");
}
}else {
schmollMode="OnlineRemote";//在线
Machine.toggleBtn.setText("CIM ON");
for (JButton jButton:StyleProperties.limitList){
jButton.setEnabled(true);
System.out.println("在线激活");
}
}
//机台当前控制模式
String strcmr = EekpMesReply.mesEquipmentControlMode();
StyleProperties.mainFrame.httpClientSocket.send(strcmr);
System.out.println("远程控制模式:"+ModeMsg+"\n"+schmollMode);
String mes = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<schmoll_mes_message version=\"1\">\n" +
" <cmd_type>Write</cmd_type>\n" +
" <cmd_id>common.MesMode</cmd_id>\n" +
" <cmd_variant>0</cmd_variant>\n" +
" <msg_id>1</msg_id>\n" +
" <msg_result>0</msg_result>\n" +
" <sender_id>Machine #10124</sender_id>\n" +
" <receiver_id>MES Servername</receiver_id>\n" +
" <msg_timestamp>2018-02-01T18:30:01.000+01:00</msg_timestamp>\n" +
" <data_timestamp>2018-02-01T18:30:00.000+01:00</data_timestamp>\n" +
" <data> \n" +
" <current_mode>Offline</current_mode>\n" +
" <mode>"+schmollMode+"</mode>\n" +
" </data>\n" +
"</schmoll_mes_message>\n";
// 离线本地Offline 在线远程OnlineRemote
mes = "SMDATMSG,1,schmoll_mes_message,application/xml,"+mes.length()+"\n" +
mes +
"\nSMDATEND";
// mainFrame.schmollClientImpl.send(mes);
}
//机台当前控制模式
if(messagename.equals("EquipmentControlMode")){
String strcmr = EekpMesReply.mesEquipmentControlModeReply();
StyleProperties.mainFrame.httpClientSocket.send(strcmr);
}
//4.3Date Time Sync Command 时间校对
if (messagename.equals("DateTimeSyncCommand")) {
int beginDT=requestString.indexOf("<date_time>");
int endDT=requestString.indexOf("</date_time>");
String date_time = requestString.substring(beginDT+"<date_time>".length() ,endDT);
String str = EekpMesReply.mesDateTimeSyncReply(date_time);
StyleProperties.mainFrame.httpClientSocket.send(str);
String ts = tsFormat.format(new Date());
String mes = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<schmoll_mes_message version=\"1\">\n" +
" <cmd_type>Write</cmd_type>\n" +
" <cmd_id>common.Time</cmd_id>\n" +
" <cmd_variant>0</cmd_variant>\n" +
" <msg_id>-1</msg_id>\n" +
" <msg_result>1</msg_result>\n" +
" <sender_id>MES Server</sender_id>\n" +
" <receiver_id>"+ StyleProperties.machineID +"</receiver_id>\n" +
" <msg_timestamp>"+ ts.substring(0, 26) + ":" + ts.substring(26) +"</msg_timestamp>\n" +
" <data_timestamp>"+ ts.substring(0, 26) + ":" + ts.substring(26) +"</data_timestamp>\n" +
"</schmoll_mes_message>";
mes = "SMDATMSG,1,schmoll_mes_message,application/xml,"+mes.length()+"\n" +
mes + "\nSMDATEND";
// mainFrame.schmollClientImpl.send(mes);
}
//4.2Initial Data Request 初始化数据
if (messagename.equals("InitialDataRequest")) {
String str = EekpMesReply.mesInitialDataReply();
StyleProperties.mainFrame.httpClientSocket.send(str);
}
//camPath
if (messagename.equals("TraceDataRequest")){
String str = EekpMesReply.mesTraceDataRequestReply();
StyleProperties.mainFrame.httpClientSocket.send(str);
}
//4.12 Operator Login Confirm 1:OK 2:NG (登录页面提交后,客户服务端 返回 是否通过 登录)
if(messagename.equals("OperatorLoginConfirm")){
return_result = StringUtil.substr("<confirm_result>", "</confirm_result>", requestString);
String str = EekpMesReply.mesOperatorLoginConfirmReply();
StyleProperties.mainFrame.httpClientSocket.send(str);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
//发送
public String send(String StringIn) {
System.out.println("回复数据String:\n" + StringIn);
logger.info("eekp send] -> " +StringIn);
try {
FileMethod.machine((new Date() + "eekp_send---> " + StringIn)); //发送
}catch (Exception e){
e.printStackTrace();
}
try {
Thread.sleep(1000);
byte[] bytes = StringIn.getBytes(StandardCharsets.UTF_16LE);
byte[] data = new byte[bytes.length+2];
data[0] = 0x02;
System.arraycopy(bytes,0,data,1,bytes.length);
data[data.length-1] = 0x03;
if(HttpClientSocket.httpClientbRun){
outStream.write(data);
outStream.flush();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
System.out.println("reply ok");
return null;
}
public static void main(String[] args) {
// ClientSocket("你好");
// System.out.println(Arrays.toString("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n".getBytes(StandardCharsets.UTF_16LE)));
System.out.println(System.getProperty("user.dir") + File.separator + "file.txt");
}
//判断字符串的编码格式
public static String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s = encode;
return s;
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return "";
}
//将不同编码格式转为UTF-8显示出来
public static String toChinese(String strvalue, String encodeFormat) {
try {
if (strvalue == null) {
return "";
} else {
strvalue = new String(strvalue.getBytes(encodeFormat), "UTF-8").trim();
return strvalue;
}
} catch (Exception e) {
return "";
}
}
/**
* 菱形
* @param size
*/
public static void print(int size) {
if (size % 2 == 0) {
size++; // 计算菱形大小
}
for (int i = 0; i < size / 2 + 1; i++) {
for (int j = size / 2 + 1; j > i + 1; j--) {
System.out.print(" "); // 输出左上角位置的空白
}
for (int j = 0; j < 2 * i + 1; j++) {
System.out.print("*"); // 输出菱形上半部边缘
}
System.out.println(); // 换行
}
for (int i = size / 2 + 1; i < size; i++) {
for (int j = 0; j < i - size / 2; j++) {
System.out.print(" "); // 输出菱形左下角空白
}
for (int j = 0; j < 2 * size - 1 - 2 * i; j++) {
System.out.print("*"); // 输出菱形下半部边缘
}
System.out.println(); // 换行
}
}
}
class Dialog extends JDialog {
Dialog() {
this.setTitle("提示信息!");
this.setVisible(true);
this.setLocation(200, 200);
this.setSize(400, 300);
Container contentPane = this.getContentPane();
JLabel jLabel = new JLabel(HttpClientSocket.cim_message);
contentPane.add(jLabel);
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
}
}
·····X1·····
···················································································································································································