如何在 Java 中获取当前工作目录

本教程介绍了如何获取当前工作目录,并列举了一些示例代码来理解。

获取当前工作目录的方法有几种,这里我们用到了 System.getProperty()toAbsolutePath()FileSystems.getDefault() 等方法。我们来看看实例。

在 Java 中使用 System.getProperty() 方法获取当前工作目录

System.getProperty() 方法是返回由键(参数)表示的系统属性。例如,user.dir 返回用户目录,os.name 返回操作系统的名称。这里,我们用这个方法来获取当前用户工作目录。请看下面的例子。

public class SimpleTesting {
	public static void main(String[] args) {
		String directoryName = System.getProperty("user.dir");
		System.out.println("Current Working Directory is = " +directoryName);
	}
}

输出:

Current Working Directory is = D:\eclipse-workspace\corejavaexamples

使用 Java 中的 toAbsolutePath() 获取当前工作目录

toAbsolutePath() 方法可以获得任何位置的绝对路径。这里,我们用这个方法来获取当前目录的绝对路径。请看下面的例子。

import java.nio.file.Path;
import java.nio.file.Paths;
public class SimpleTesting {
	public static void main(String[] args) {
		Path path = Paths.get("");
		String directoryName = path.toAbsolutePath().toString();
		System.out.println("Current Working Directory is = " +directoryName);
	}
}

输出:

Current Working Directory is = D:\eclipse-workspace\corejavaexamples

使用 Java 中的 normalize() 方法获取当前工作目录

normalize() 方法从当前路径返回一个路径,在这个路径中,所有多余的名称元素都被删除。我们将此方法与 toAbsolute() 方法一起使用,通过消除多余的名称来获得当前工作目录。请看下面的例子。

import java.nio.file.Path;
import java.nio.file.Paths;
public class SimpleTesting {
	public static void main(String[] args) {
		Path path = Paths.get("");
		String directoryName = path.toAbsolutePath().normalize().toString();
		System.out.println("Current Working Directory is = " +directoryName);
	}
}

输出:

Current Working Directory is = D:\eclipse-workspace\corejavaexamples

在 Java 中使用 FileSystems.getDefault() 方法获取当前工作目录

我们可以使用 FileSystem 类的 getDefault() 方法来获取默认的 Filesystem,然后使用 toAbsolutePath() 方法来获取当前工作目录的绝对路径。请看下面的例子。

import java.nio.file.FileSystems;
import java.nio.file.Path;
public class SimpleTesting {
	public static void main(String[] args) {
		Path path = FileSystems.getDefault().getPath("");
		String directoryName = path.toAbsolutePath().toString();
		System.out.println("Current Working Directory is = " +directoryName);
	}
}

输出:

Current Working Directory is = D:\eclipse-workspace\corejavaexamples

使用 Java 中的 getAbsoluteFile() 方法获取当前工作目录

我们可以使用 getAbsoluteFile() 方法来获取当前文件的位置,实际代表当前目录的位置。请看下面的例子。

import java.io.File;
public class SimpleTesting {
	public static void main(String[] args) {
		File file = new File("");
		String directoryName = file.getAbsoluteFile().toString();
		System.out.println("Current Working Directory is = " +directoryName);
	}
}

输出:

Current Working Directory is = D:\eclipse-workspace\corejavaexamples

在 Java 中使用 getClass() 方法获取当前的工作目录

我们可以使用 Java 中 Object 类的 getClass() 方法来返回当前正在运行的类,进一步可以用 getPath() 方法来获取当前工作目录的路径。请看下面的例子。

public class SimpleTesting {
	String getCurrentDirectory() {
		return this.getClass().getClassLoader().getResource("").getPath();
	}
	public static void main(String[] args) {
		String directoryName = new SimpleTesting().getCurrentDirectory();
		System.out.println("Current Working Directory is = " +directoryName);
	}
}

输出:

Current Working Directory is = D:\eclipse-workspace\corejavaexamples

如何在 Java 中获取当前的日期时间

我们将介绍 Java 中可以获取当前日期时间的各种方法。我们将看到详细的例子,以便更好地理解事情。

在 Java 中 LocalDateTime.now() 获取当前日期和时间的方法

我们可以使用 LocaleDateTime 类的 now() 方法获得当前的日期-时间。它以 YYYY-MM-DD-hh-mm-ss.zz 格式返回日期和时间,比如 2020-09-22T14:39:33.889798

为了使它更容易阅读,我们将使用 DateTimeFormatter.ofPattern(pattern),它需要一个日期-时间模式,我们可以根据我们的需要定制。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        System.out.println("yyyy/MM/dd HH:mm:ss-> "+dtf.format(LocalDateTime.now()));
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss");
        System.out.println("yy/MM/dd HH:mm:ss-> "+dtf2.format(LocalDateTime.now()));
        DateTimeFormatter dtf3 = DateTimeFormatter.ofPattern("yyyy/MMMM/dd HH:mm:ss");
        System.out.println("yyyy/MMMM/dd HH:mm:ss-> "+dtf3.format(LocalDateTime.now()));
        DateTimeFormatter dtf4 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
        System.out.println("yyyy/MM/dd HH:mm-> "+dtf4.format(LocalDateTime.now()));
        DateTimeFormatter dtf5 = DateTimeFormatter.ofPattern("yyyy/MM/dd hh:mm");
        System.out.println("yyyy/MM/dd hh:mm:ss-> "+dtf5.format(LocalDateTime.now()));
    }
}

输出:

yyyy/MM/dd HH:mm:ss-> 2020/09/22 15:07:01
yy/MM/dd HH:mm:ss-> 20/09/22 15:07:01
yyyy/MMMM/dd HH:mm:ss-> 2020/September/22 15:07:01
yyyy/MM/dd HH:mm-> 2020/09/22 15:07
yyyy/MM/dd hh:mm:ss-> 2020/09/22 03:07

在 Java 中 ZonedDateTime.now() 获取带有时区的当前日期和时间

时区是日期和时间的一个重要部分,我们可以使用 ZonedDateTime.now() 来获取带有时区的日期时间。我们可以使用 ZonedDateTime.now() 获得带有时区的日期时间。

这还不是全部,因为我们可以通过在 ZonedDateTime.now() 中传递 ZoneId 参数来获得每个时区的时间。

请看下面的例子。

import java.time.ZonedDateTime;
public class Main {
    public static void main(String[] args) {
        System.out.println(ZonedDateTime.now());
       System.out.println("Get current timezone "+ZonedDateTime.now().getZone());
        System.out.println("Get time of different timezone: "+ZonedDateTime.now(ZoneId.of("America/New_York")));
    }
}

输出:

2020-09-22T15:53:32.635585+05:30[Asia/Kolkata]
Get current timezone Asia/Kolkata
Get time of different timezone: 2020-09-22T06:23:32.643391-04:00[America/New_York]

在 Java 中 Calendar.getInstance() 获取当前日期和时间

另一种获取当前日期/时间的方法是使用 Calendar.getInstance() 返回一个带有当前日期和时间的 Calendar 对象,可以使用 getTime() 方法将其转换为 Date/Time 格式。

我们可以看到示例中显示了日期时间。

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
    public static void main(String[] args) {
 String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
        System.out.println(timeStamp);
    }
}

输出:

2020/09/22 15:59:45

如何在 JavaScript 中获取对象的长度

我们想在 JavaScript 中获得一个对象的长度,但对象没有长度属性。只有数组和字符串才有 length 属性。

let object1 = {name: "Mark", age:30};
let string1 = 'Delftstack';
let array1 = [1,2,3];
console.log(object1.length);
console.log(string1.length);
console.log(array1.length);

输出:

undefined
10 
3

我们将介绍不同的方法来获取 JavaScript 中对象的长度。

使用 Object.keys() 方法来获取 JavaScript 中对象的长度

Object.keys() 方法返回一个 Object 的属性数组。我们使用 length 属性来获取键的数量。

例子:

const getLengthOfObject = (obj) => {
  let lengthOfObject = Object.keys(obj).length; 
  console.log(lengthOfObject);
}

getLengthOfObject({ id: 1, name: 'Mark', age: 30 } );

输出:

3

在 JavaScript 中使用 for...in 循环来获取一个对象的长度

它迭代对象的属性,并将在循环中增加属性的计数器。

例子

const getLengthOfObject = (obj) => {
  
  let length0fObject = 0;
  
  for(let key in obj){
    length0fObject++;
  }

  console.log(length0fObject);
  return length0fObject;
} 

getLengthOfObject({ id: 1, name: 'Mark', age: 30 } );

输出:

3

示例:输出

const getLengthOfObject = (obj) => {
  
  let length0fObject = 0;
  
  for(let key in obj){
     if (obj.hasOwnProperty(key)){
           length0fObject++;
     }
  }

  console.log(length0fObject);
  return length0fObject;
} 

getLengthOfObject({ id: 1, name: 'Mark', age: 30, country: "USA", job: "software developer" } );

hasOwnProperty() 函数是 JavaScript 中的一个内置函数,用于检查对象是否拥有指定的属性,它根据对象是否拥有指定的属性返回 true 或 false