【问题标题】:How can System.currentTimeMillis return longs with different lengths in a short period of time?System.currentTimeMillis 如何在短时间内返回不同长度的多头?
【发布时间】:2018-08-16 18:15:11
【问题描述】:

我正在创建临时目录

Files.createTempDirectory(String.format("project-it-screenshots-%d",
        System.currentTimeMillis())).toFile();

我假设System.currentTimeMillis() 返回的longs 都具有相同的长度,因为具有不同长度的两个返回值必须来自不同的世纪。每天多次调用该方法后,我最终得到了

project-it-screenshots-15343380422205011345585140911467
project-it-screenshots-15343381444485756307954062111474
project-it-screenshots-15343386111604255833362898885857
project-it-screenshots-15343388402055473274775132302475
project-it-screenshots-1534338974370463603854456850155
project-it-screenshots-15343390449093279576023746896269
project-it-screenshots-15343398036346426501075034038757
project-it-screenshots-15343399888498609875231360701639
project-it-screenshots-15343401211515574289310135012571
project-it-screenshots-15343405563586337945661543042110
project-it-screenshots-15343419027757787065954653813302
project-it-screenshots-15343425353682119990056938907868
project-it-screenshots-15343429571018010152043055630277
project-it-screenshots-15343431608662744493593200651167
project-it-screenshots-15343436122094379676346949668973
project-it-screenshots-15343442103124076542522856351947
project-it-screenshots-15343539846818150078805796257638
project-it-screenshots-15343555678106536264262565060437
project-it-screenshots-15343809068582300780873443756155
project-it-screenshots-15344378068483088975615680511653
project-it-screenshots-15344421866441533761733546877922

其中1534338974370463603854456850155 比其他数字短一位。这似乎与剥离前导 0s 无关,因为没有,也与尾随 0s 无关,因为一些长度较大的数字有它们,而另一些则没有。

我正在寻找解释,而不是解决方法(我将使用可以排序的格式化日期或将0 填充到带有String.format 的数字中,这只会稍微改变时间戳)。

我在 Ubuntu 18.04 上使用 OpenJDK 8。

【问题讨论】:

  • createTempDirectory 添加了一堆“唯一”后缀字符,这取决于实现,未指定。见stackoverflow.com/questions/9594886/…
  • 在您的所有示例中,currentTimeMillis 的结果已进入前 13 位(不多也不少),例如 15343380422201534338974370。你所有的毫秒值形成了一个很好的递增序列。

标签: java timestamp digit current-time


【解决方案1】:

System.currentTimeMillis() 方法返回一个long,它最多只能是 19 位长。但是您的数字字符串长度为 31-32 个字符。

Files.createTempDirectory() 的调用正在为您的文件名添加其他字符。

在默认临时文件目录中创建一个新目录,使用给定的前缀生成其名称。

(我的粗体强调)

此方法的工作方式与createTempDirectory(Path,String,FileAttribute[]) 方法在dir 参数为临时文件目录的情况下完全一样。

该方法指出:

关于如何构建目录名称的详细信息取决于实现,因此未指定。

如果您希望名称可预测,则不能使用Files 中的任何“createTemp”方法。如果您对后缀不在您的控制范围内感到满意,那么如何创建前缀是可选的。但是使用System.currentTimeMillis() 并不是路径名比另一个短的原因。一定是实现,没有具体说明。

在 Windows 10 上,我得到了类似的东西。

C:\Users\rgettman\AppData\Local\Temp\project-it-screenshots-15344437949188484678689730417470

【讨论】:

    猜你喜欢
    • 2017-09-12
    • 2012-02-27
    • 2013-06-20
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    相关资源
    最近更新 更多