系统接口

系统信息

String os_name = System.getProperty("os.name")

日期和时间

import java.time.*;

LocalDate封装日期,LocalTime封装时间,LocalDateTime封装日期和时间的组合。

按使用场景选择相应的类型,不能访问类型未封装的时间字段。

获取当前日期时间:

LocalDateTime datetime = LocalDateTime.now();

设定一个日期时间:

LocalDate date_set = LocalDate.of(2020, 2, 19);

修改日期时间对象:

datetime = datetime.withYear(2077).withDayOfMonth(1).withMonth(10);
datetime.plusYears(1);  // plus() method series
datetime.minusSeconds(seconds); // minus() method series

获取日期时间中的字段:

get(TemporalField field)
datetime.getYear(); // get() method series

格式和解析

DateTimeFormatter设置日期时间的格式:

formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
System.out.println(datetime.format(formatter));

设定的格式也可以用于时间字符串的解析:

date_parse = LocalDateTime.parse("12-03-2010 11:22:33", formatter);

时间间隔

Duration

Duration.between(datetime1, datetime2);

时间戳(Timestamp)

Instant

Instant timestamp = Instant.parse(date.toString());
System.out.println("Timestamp: " + timestamp.toString());

旧式API

Date表示一个时间点,精确到毫秒,相当于存储一个整数值。

import java.util.Date;
Date d = new Date();	// 获取当前日期和时间
Date d = new Date(long millisec);  //指定从1970年1月1日00:00:00开始的毫秒数

Date的初始化可以通过指定年月日获字符串表达式等的方式设置,但是这些设置方式已被废弃,这些设置方式可以用在CalenderDateFormat类中。

int compareTo(Date anotherDate)

使本对象与另一个时间比较。

long getTime()
void setTime(long time)

获取/设置时间。

Calendar按照日历的表示形式来设置和获取日期。 Calendar是抽象类,不能用构造函数初始化;Calendar的表达与地区有关,使用getInstance()来获取合适的子类实例作为Calendar引用的对象。

import java.util.Calendar;
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR)  // MONTH, DAY_OF_MONTH, HOUR_OF_DAY, MINUTE, ...

使用set()add()roll()可以改变字段的值。

  • set(f, value)设置指定字段f的值。

  • add(f, delta)增加指定字段f的值,如果超过了该字段的最大值,则会发生进位。

  • roll(f, delta)add一样,只是不会改变上一级字段的值。

利用Time获取:唯一不足是取出时间只有24小时模式。

import java.util.Time;
Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。
t.setToNow(); // 取得系统时间。
int year = t.year; // month, monthDay, hour, minute, second

DateFormat表示日期或时间格式的抽象类。

import java.text.SimpleDateFormat;
SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm:ss ");
String str = formatter.format(Date());

当然还有就是可以指定时区的时间:

df=DateFormat.getDateTimeInstance(DateFormat.FULL,Locale.CHINA);
System.out.println(df.format(new Date()));

文件管理

目录和文件管理由File类实现。

package java.io;
public class File implements java.io.Serializable, java.lang.Comparable

每个File对象对应与一个磁盘文件或目录(以下统称文件),通过其字段可以查询对应文件的相关信息,调用它的方法可完成对文件或目录的常用操作,如创建、删除等。

创建File对象

File(String pathname)		//使用文件或目录名创建对象
File(String parent,String child)//使用父目录+子目录创建对象
File(File parent,String child)//使用父目录对象+子目录创建对象
File(URI uri)		//使用URI(同一资源标识符)创建对象

由于Windows系统中使用\作为分隔符,容易与转义字符发生混淆,所以在路径名中使用\\代替\,而在UNIX等系统中则使用/。当书写路径名或以驱动器名开头时,代表绝对路径;以\\/开头,也代表绝对路径,此时驱动器默认为当前工作目录所在驱动器;若以...或其他单词开头则代表相对路径。

获取文件的属性

 boolean exists()
 boolean isDirectory()
 boolean isFile()

exists()判断文件是否存在;isDirectory()判断文件目录是否为目录;isFile()判断文件是否为普通文件。

String getName()
String getPath()
String getAbsolutePath()
String getParent()

getName()返回文件名;getPath()返回文件路径(根据构造函数给的是相对路径还是绝对路径决定),等效于toString()getAbsolutePath()返回绝对路径;getParent()返回父目录的路径。

String[] list()
File[] listFiles()

list()列出目录下的所有文件和目录;listFiles()列出目录下的所有普通文件。

如果对像不是目录或是空目录则返回null

boolean canRead()
boolean canWrite()

获取文件的读写权限。

long length()

获取文件的长度(对与目录则返回值无意义)。

文件操作

boolean renameTo(File dest)

将文件或目录的名称改为指定的名称(移动文件或目录),该操作是平台相关的,可能造成文件不能从一个文件系统移动到另一个文件系统,另外如果目标路径已经存在,则不能完成移动。根据返回值确定移动操作是否成功进行。

boolean delete()

删除文件或目录,如果是目录,则目录必须为空才能执行删除。

boolean mkdir()
boolean mkdirs()

创建目录,返回是否创建成功。

mkdir()要求文件的父目录存在;mkdirs()在父目录不存在的情况下先创建父目录。

boolean createNewFile()  // return true if file not exist and created.

仅在文件不存在时创建新文件,文件的父目录必须存在。

注意File对象本身只是对磁盘文件/目录的映射,并不代表相应的文件实际存在或已被打开。

进程和线程

创建进程

执行系统命令

使用Runtime
Runtime rt = Runtime.getRuntime();
Process ps = rt.exec(cmd_string);
int exitCode = ps.waitFor();

https://www.javaworld.com/article/2071275/when-runtime-exec---won-t.html

使用ProcessBuilder
ProcessBuilder builder = new ProcessBuilder();
builder.command("cmd.exe", "/c", "dir");	// "sh" for linux
builder.directory(new File(System.getProperty("user.home")));
Process process = builder.start();
int exitCode = process.waitFor();
命令的输出

the output must be consumed – otherwise the process doesn't return successfully, instead it will hang.

StreamGobbler streamGobbler = 
  new StreamGobbler(process.getInputStream(), System.out::println);
// process.getErrorStream()
Executors.newSingleThreadExecutor().submit(streamGobbler);

创建线程

Multithreading in Java - Everything You MUST Know - JournalDev

Java Thread Example - JournalDev

Java 提供了三种创建线程的方法:

  • 继承 Thread类,实现run()方法:

    class MyThread extends Thread{
    	public void run(){
    		while(true){
    			System.out.println("MyThread类的run()方法在运行");
    		}
    	}
    }
    MyThread myThread=new MyThread();
    myThread.start();
    
  • 继承 Runnable接口并实现run()方法的类。可以使用Lambda表达式定义函数接口。

    Runnable runnable = () -> {
       while(true){
          System.out.println("MyThread类的run()方法在运行");
       }
    }
    runnable.start();  // => thread.start(new Thread(runnable));
    
  • 通过 CallableFuture创建线程。

    Callable一般是和ExecutorService配合来使用的

    <T> Future<T> submit(Callable<T> task);
    <T> Future<T> submit(Runnable task, T result);
    Future<?> submit(Runnable task);
    

    Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。

    public interface RunnableFuture<V> extends Runnable, Future<V> {
        void run();
    }
    public class FutureTask<V> implements RunnableFuture<V>
    

    Java并发编程:Callable、Future和FutureTask

    Java Callable Future Example - JournalDev