Java中的一些基础代码片段_4


=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() : "";
        }
    }

}

 

参考链接:

=END=


《 “Java中的一些基础代码片段_4” 》 有 14 条评论

  1. [原]Java在内存中将Map打包为tar.gz
    https://blog.csdn.net/dutsoft/article/details/80397154
    `
    近期需要将一些数据数据打成tar.gz包,放到ftp上供合作方拉取。在网上查了下Java打包文件的方式,发现很多例子都是基于文件操作进行了。在实际业务中,并不需要将文件落盘,只需放到ftp即可。为了保证效率,打包时最好不写本地磁盘,完全在内存中进行。下面的例子,简单演示了将Map打包为tar.gz字节流。
    `

  2. 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

  3. 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
    `

  4. 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));
    `

  5. 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
    `

  6. 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());
    `

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注