【问题标题】:Android: How to get & set directory modification dateAndroid:如何获取和设置目录修改日期
【发布时间】:2012-06-13 05:35:24
【问题描述】:

我正在寻找一种获取目录修改日期的方法。我试过了:

File dir = new File(myDir);
long mod = dir.lastModified();

但它返回 0。

我也在寻找一种方法来设置目录的最后修改日期,但没有找到任何东西。

是否有记录的方法来执行这些操作?

【问题讨论】:

    标签: android file directory


    【解决方案1】:

    编辑: 您的代码看起来正确,只需检查目录是否存在..

    public long lastModified ()
    

    返回上次修改此文件的时间,以 1970 年 1 月 1 日午夜以来的毫秒数为单位。 如果文件不存在则返回 0。

    所以只需检查您的文件是否存在..

    代码:

    从文件中获取上次修改日期,

    File file = new File("Your file path");
    Date lastModDate = new Date(file.lastModified());
    Log.i("File last modified : "+ lastModDate.toString());
    

    将上次修改日期设置为文件..

    try{
    
        File file = new File("/mnt/sdcard/temp.txt");
    
        //print the original last modified date
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Log.i("Original Last Modified Date : " , ""+sdf.format(file.lastModified()));
    
        //set this date 
        String newLastModified = "01/06/2012";
    
        //need convert the above date to milliseconds in long value 
        Date newDate = sdf.parse(newLastModified);
        file.setLastModified(newDate.getTime());
    
        //print the latest last modified date
        Log.i("Lastest Last Modified Date : ", ""+sdf.format(file.lastModified()));
    
        }catch(ParseException e){
            e.printStackTrace();
        }
    

    【讨论】:

      【解决方案2】:

      我希望你的 myDir 包含目录的路径

      以下 sn-p 对我有用

              File file1 = new File(getFilesDir().getAbsolutePath());
              Log.i("text", "" + file1.lastModified());
      

      【讨论】:

        【解决方案3】:

        object dir 返回的 long 变量需要如下转换,使用您的示例。

        File dir = new File(myDir);
        long mod = dir.lastModified();
        Date lastModify = new Date(mod);
        

        对于日期设置,请尝试函数 setLastModified( long Time )。

        供参考,一个Java链接@Java 1.7

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多