=Start=
缘由:
在学习Java的过程中不断用文章进行整理总结(常用功能的Java实现),争取早日能较为熟练的使用Java进行开发。
这一篇主要是对Java杂项知识的一个整理和总结。
正文:
参考解答:
1. 三元操作符;
package com.ixyzero.learn.misc; /** * (条件表达式) ? 表达式1 : 表达式2; * 当 (条件表达式) 为 True 时, 执行 表达式1 ; 为 False 时,执行 表达式2 。 */ public class TestTernaryOperator { public static void main(String[] args) { int a = 1; int b = 5; System.out.println("a = " + a + "\nb = " + b); int c; c = ("" == null || true != false) ? a : b; System.out.println("\nc = " + c); System.out.println(); System.out.println("'\"\" == null' is " + ("" == null)); System.out.println("'true != false' is " + (true != false)); } }
2. static 语句块的初始化顺序;
package com.ixyzero.learn.misc; /** * Java里面一个class它的初始化顺序是? 先 static 再 init 呢?还是直接 init 呢? 结论: 先 static 再 main/init 。 * print in class static code block print in main method print in class init method hello * */ public class TestStatic { static { System.out.println("print in class static code block"); } private TestStatic() { System.out.println("print in class init method"); } private void hello() { System.out.println("hello"); } public static void main(String[] args) { System.out.println("print in main method"); TestStatic testStatic = new TestStatic(); testStatic.hello(); } }
3. 快速打印当前日期时间的方式;
package com.ixyzero.learn.misc; import java.text.SimpleDateFormat; public class TestSubstring { public static void main(String[] args) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentDateTime = df.format(System.currentTimeMillis()); System.out.println(df.toString()); // java.text.SimpleDateFormat@4f76f1a0 System.out.println(currentDateTime); // 2018-06-16 16:56:32 } }
4. 类型转换的一些情形总结;
package com.ixyzero.learn.misc; public class TestConvert { private static Object returnType() { return true; // return "haha"; // java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean } private static Object returnType2() { // return true; // java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String return ""; } public static void main(String[] args) { boolean tag = (Boolean) returnType(); if (tag) { System.out.println("tag is '" + tag + "'"); } else { System.out.println("tag is '" + tag + "'"); } String tagStr = (String) returnType2(); if (tagStr != null && !tagStr.isEmpty()) { System.out.println("tagStr is '" + tagStr + "'"); } else { System.out.println("tagStr is '" + tagStr + "'"); } } }
5. 获取主机名的方法;
package com.ixyzero.learn.misc; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Scanner; public class TestgetHostName { public static void main(String[] args) { String hostname = null; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } System.out.println("InetAddress.getLocalHost().getHostName() = " + hostname); String os = System.getProperty("os.name").toLowerCase(); System.out.println("String os = System.getProperty(\"os.name\").toLowerCase() = " + os); if (os.contains("win")) { try { System.out.println("Windows computer name through env:\"" + System.getenv("COMPUTERNAME") + "\""); System.out.println("Windows computer name through exec:\"" + execReadToString("hostname") + "\""); } catch (IOException e) { e.printStackTrace(); } } else if (os.contains("nix") || os.contains("nux") || os.contains("mac os x")) { try { System.out.println("Unix-like computer name through env:\"" + System.getenv("HOSTNAME") + "\""); System.out.println("Unix-like computer name through exec:\"" + execReadToString("hostname") + "\""); System.out.println("Unix-like computer name through /etc/hostname:\"" + execReadToString("cat /etc/hostname") + "\""); } catch (IOException e) { e.printStackTrace(); } } } public static String execReadToString(String execCommand) throws IOException { try (Scanner s = new Scanner(Runtime.getRuntime().exec(execCommand).getInputStream()).useDelimiter("\\A")) { return s.hasNext() ? s.next() : ""; } } }
参考链接:
- 【Java】(三)运算符小结(比较、逻辑、三元运算符)
- java 静态代码块执行顺序
- java中静态代码块的用法 static用法详解
- Recommended way to get hostname in Java
=END=
《 “Java中的一些基础代码片段_4” 》 有 14 条评论
[原]Java在内存中将Map打包为tar.gz
https://blog.csdn.net/dutsoft/article/details/80397154
`
近期需要将一些数据数据打成tar.gz包,放到ftp上供合作方拉取。在网上查了下Java打包文件的方式,发现很多例子都是基于文件操作进行了。在实际业务中,并不需要将文件落盘,只需放到ftp即可。为了保证效率,打包时最好不写本地磁盘,完全在内存中进行。下面的例子,简单演示了将Map打包为tar.gz字节流。
`
Java 枚举7常见种用法
http://blog.lichengwu.cn/java/2011/09/26/the-usage-of-enum-in-java/
http://softbeta.iteye.com/blog/1185573
Java 语言中 Enum 类型的使用介绍
https://www.ibm.com/developerworks/cn/java/j-lo-enum/index.html
Java enum的用法详解
https://www.cnblogs.com/happyPawpaw/archive/2013/04/09/3009553.html
Java枚举详解
https://www.jianshu.com/p/6f2f5627c27d
Java的枚举类型用法介绍
http://www.hollischuang.com/archives/195
Java 枚举知识整理
http://blinkfox.com/java-mei-ju-zhi-shi-zheng-li/
java 枚举类比较是用==还是equals?
https://blog.csdn.net/qq_27093465/article/details/70237349
URL短网址生成算法原理
https://blog.mimvp.com/article/25420.html
Java中如何在for循环中同时获取「index索引」和「key元素」
https://stackoverflow.com/questions/3431529/java-how-do-i-get-current-index-key-in-for-each-loop
`
// 使用 foreach 循环
int index = 0;
for(Element song : question) {
System.out.println(“Current index is: ” + (index++));
}
// 或常规的 for 循环
for(int i = 0; i < question.length; i++) {
System.out.println("Current index is: " + i);
}
`
Java 8 forEach with index
https://stackoverflow.com/questions/22793006/java-8-foreach-with-index
https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8
Java – How to get current date time(获取当前日期时间)
https://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
`
// 方法一
DateFormat dateFormat = new SimpleDateFormat(“yyyy/MM/dd HH:mm:ss”);
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
// 方法二
DateFormat dateFormat = new SimpleDateFormat(“yyyy/MM/dd HH:mm:ss”);
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
// 方法三(Java 8及以上版本)
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(“yyyy/MM/dd HH:mm:ss”);
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43
// 方法四(Java 8及以上版本)
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(“yyyy/MM/dd”);
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16
`
Java中如何获取1小时之前的日期时间
https://stackoverflow.com/questions/8833399/changing-java-date-one-hour-back
`
#(方法一) java.util.Calendar
Calendar cal = Calendar.getInstance();
// remove next line if you’re always using the current time.
cal.setTime(currentDate);
cal.add(Calendar.HOUR, -1);
Date oneHourBack = cal.getTime();
#(方法二) java.util.Date
new Date(System.currentTimeMillis() – 3600 * 1000);
#(方法三) org.joda.time.LocalDateTime
new LocalDateTime().minusHours(1)
#(方法四) Java 8: java.time.LocalDateTime
LocalDateTime.now().minusHours(1)
#(方法五) Java 8: java.time.Instant
// always in UTC if not timezone set
Instant.now().minus(1, ChronoUnit.HOURS));
// with timezone, Europe/Berlin for example
Instant.now()
.atZone(ZoneId.of(“Europe/Berlin”))
.minusHours(1));
`
Adding n hours to a date in Java?
https://stackoverflow.com/questions/3581258/adding-n-hours-to-a-date-in-java
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html
https://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html
EasyExcel 轻松灵活读取Excel内容
https://segmentfault.com/a/1190000020759658
https://dayarch.top/p/61d8a472.html
超级好用的 Java 数据可视化库:Tablesaw
https://mp.weixin.qq.com/s/gSHwCvOM_epBO0VSZaGirQ
https://github.com/jtablesaw/tablesaw
`
Tablesaw是一款 Java 的数据可视化库。它主要包括两部分:一部分是数据解析库,另一部分是数据可视化库。数据解析库主要是加载数据,对数据进行操作(转化,过滤,汇总等)。数据可视化库就是将目标数据转化为可视化的图表。
`
Java中set在创建时的初始化
https://stackoverflow.com/questions/2041778/how-to-initialize-hashset-values-by-construction
`
// 一行版本(在不考虑效率的情况下)
Set h = new HashSet(Arrays.asList(“a”, “b”));
// 静态初始化
public static final String[] SET_VALUES = new String[] { “a”, “b” };
public static final Set MY_SET = new HashSet(Arrays.asList(SET_VALUES));
`
Java中如何操作Excel
https://mvnrepository.com/artifact/org.apache.poi/poi
https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml
How to Read Excel Files in Java using Apache POI #读
https://www.codejava.net/coding/how-to-read-excel-files-in-java-using-apache-poi
How to Write Excel Files in Java using Apache POI #写
https://www.codejava.net/coding/how-to-write-excel-files-in-java-using-apache-poi
`
# 写Excel的基本步骤
1. 创建一个 workbook
2. 创建一个 sheet
3. 重复如下步骤直到数据被写入完成:
* 创建一个 row
* 在 row 中创建 cells ,如果要设置格式的话可以用 CellStyle
4. 将 workbook 写入 FileOutputStream
5. 关闭 FileOutputStream
`
Reading and Writing data to excel file using Apache POI
https://www.geeksforgeeks.org/reading-writing-data-excel-file-using-apache-poi/
https://mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/
This module contains articles about Apache POI
https://github.com/eugenp/tutorials/tree/master/apache-poi
https://stackoverflow.com/questions/3454975/writing-to-excel-in-java
Java Set集合详解及Set与List的区别
https://blog.csdn.net/xiaoxiaovbb/article/details/80439643
`
实际上,可以看出,set的实体类主要就是以map为基础,相对应的使用环境和意义也和对应的map相同。
那为什么会构造Set这个集合呢?
实际上就是利用map的key-value键值对的方式,通过key的唯一的特性,主要将set构建的对象放入key中,以这样的方式来使用集合的遍历一些特性,从而可以直接用Set来进行调用。
`
关于Java Set的初始化方法
https://blog.csdn.net/hebeiqiaozhonghui/article/details/87694587
`
Set tags = new HashSet();
tags.add(“111”);
tags.add(“112”);
System.out.println(tags.toString());
`