据说,在Linux系统中,文件是没有创建时间属性的,只有最后修改时间,在File对象的jdk文档中确实只有获取最后修改时间的函数,没有创建时间的函数,如下:
long lastModified() 返回此抽象路径名表示的文件最后一次被修改的时间。
示例如下:
- fun main() {
- val file = File("D:/text.txt")
- val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
- val getCurrent = { formatter.format(System.currentTimeMillis()) }
- val getFileTime = { formatter.format(file.lastModified()) }
- println("1 current = ${getCurrent()}, file = ${getFileTime()}")
-
- Thread.sleep(2000)
- if (!file.exists()) {
- file.createNewFile()
- println("2 current = ${getCurrent()}, file = ${getFileTime()}")
- }
-
- Thread.sleep(2000)
- val fos = FileOutputStream(file)
- var current = getCurrent()
- fos.write("${current}\n".toByteArray(Charsets.UTF_8))
- println("3 current = ${current}, file = ${getFileTime()}")
-
- Thread.sleep(2000)
- var read = String(FileInputStream(file).readBytes(), Charsets.UTF_8)
- println("4 current = ${getCurrent()}, file = ${getFileTime()}, read = $read")
-
- Thread.sleep(2000)
- current = getCurrent()
- fos.write("${current}\n".toByteArray(Charsets.UTF_8))
- println("5 current = ${current}, file = ${getFileTime()}")
-
- Thread.sleep(2000)
- fos.close()
- read = String(FileInputStream(file).readBytes(), Charsets.UTF_8)
- println("6 current = ${getCurrent()}, file = ${getFileTime()}, read = $read")
- }
-
输出结果如下:
- 1 current = 2021-04-14 15:13:37.469, file = 1970-01-01 08:00:00.000
- 2 current = 2021-04-14 15:13:39.479, file = 2021-04-14 15:13:39.478
- 3 current = 2021-04-14 15:13:41.494, file = 2021-04-14 15:13:41.497
- 4 current = 2021-04-14 15:13:43.511, file = 2021-04-14 15:13:41.497, read = 2021-04-14 15:13:41.494
-
- 5 current = 2021-04-14 15:13:45.514, file = 2021-04-14 15:13:45.514
- 6 current = 2021-04-14 15:13:47.528, file = 2021-04-14 15:13:45.514, read = 2021-04-14 15:13:41.494
- 2021-04-14 15:13:45.514
-
共有6行输出语句,每一行输出分析如下: