简体   繁体   English

为什么setLastModified(time)不能用于此文件?

[英]Why doesn't setLastModified(time) work for this File?

Why is the date of the file in the following code not changed? 为什么以下代码中的文件日期没有更改?

fLocal.location = Existing file in C:\\ fLocal.location = C:\\中的现有文件

fLocal.date = Date to set in Long fLocal.date =在Long中设置的日期

boolean x = new File(fLocal.location).setLastModified(Long.parseLong(fLocal.date));
System.out.println("Changed: " + x);
System.out.println(new Date(new File(fLocal.location).lastModified()));
System.out.println(new Date(Long.parseLong(fLocal.date)));

Output: 输出:

Changed: false
Fri Feb 15 23:02:51 CET 2013
Fri Feb 15 22:49:34 CET 2013

From my comments from earlier, follow these checks: 根据我之前的评论,请遵循以下检查:

  1. Does your code have write access to the file? 您的代码是否具有该文件的写入权限?
  2. Is the file in open status? 文件是否处于打开状态?
  3. Are you currently reading (or writing!) the file with any other application at the time you are doing this? 您目前是否在阅读(或撰写!)文件时使用任何其他应用程序?

These are all items that might prevent you from changing the time of the file. 这些都是可能阻止您更改文件时间的项目。

Create a simple plain text file with a single line of text, save it and close out of the editor. 使用单行文本创建一个简单的纯文本文件,保存并关闭编辑器。 Then try using that file in your application. 然后尝试在您的应用程序中使用该文件。 Make sure you call exists() on your File Object before you try to change the time of it to ensure you actually have a valid file. 在尝试更改File Object的时间之前,请确保在File Object上调用exists()以确保实际拥有有效文件。

Tested your code on my local and it works... I changed the modified date of very old file on my system... 在我的本地测试你的代码,它的工作原理...我在我的系统上更改了非常旧的文件的修改日期...

-See if file is being used somewhere else... -check if you have permissions on file - 看看文件是否正在其他地方使用... - 如果你对文件有权限,请检查

import java.io.File;
import java.io.IOException;
import java.util.Date;

class Test
{
    private class flocalClass
    {

        public String date;
        public String location="c:/Test/cascade.xyz";

    }
    public static void main (String[]args) throws IOException
    {
        flocalClass fLocal = new Test().new flocalClass();
        fLocal.date = Long.toString(new Date().getTime());
        boolean x = new File(fLocal.location).setLastModified(Long.parseLong(fLocal.date));
        System.out.println("Changed: " + x);
        System.out.println(new Date(new File(fLocal.location).lastModified()));
        System.out.println(new Date(Long.parseLong(fLocal.date)));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM