java - 在Java中设置文件创建时间戳

标签 java file date jfilechooser

我知道设置创建时间戳在 Java 中不存在,因为 Linux 没有它,但是有没有办法在 Java 中设置文件的 (Windows) 创建时间戳?我在这里制作了一个基本的修改时间戳编辑器。

import java.io.*;
import java.util.*;
import java.text.*;
import javax.swing.*;

public class chdt{
    static File file;
    static JFrame frame = new JFrame("Input a file to change");
    public static void main(String[] args) {
        try{

            final JFileChooser fc = new JFileChooser();
            fc.setMultiSelectionEnabled(false);

            //BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
            //System.out.println("Enter file name with extension:");
            //String str = bf.readLine();
            JOptionPane.showMessageDialog(null, "Input a file to change.");
            frame.setSize(300, 200);

            frame.setVisible(true);

            int retVal = fc.showOpenDialog(frame);
            if (retVal == JFileChooser.APPROVE_OPTION) {
                file = fc.getSelectedFile();
                frame.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(null, "3RR0RZ!  You didn't input a file.");
                System.exit(0);
            }

            //System.out.println("Enter last modified date in 'dd-mm-yyyy-hh-mm-ss' format:");
            //String strDate = bf.readLine();
            String strDate = JOptionPane.showInputDialog("Enter last modified date in 'dd-mm-yyyy-hh-mm-ss' format:");

            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
            Date date = sdf.parse(strDate);

            if (file.exists()){
                file.setLastModified(date.getTime());
                JOptionPane.showMessageDialog(null, "Modification is successful!");
            }
            else{
                JOptionPane.showMessageDialog(null, "File does not exist!  Did you accidentally it or what?");
            }
        }
        catch(Exception e){
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "3RR0RZ");
        }
    }
}

最佳答案

以下是在 Java 7 中使用 nio 框架的方法:

public void setFileCreationDate(String filePath, Date creationDate) throws IOException{

    BasicFileAttributeView attributes = Files.getFileAttributeView(Paths.get(filePath), BasicFileAttributeView.class);
    FileTime time = FileTime.fromMillis(creationDate.getTime());
    attributes.setTimes(time, time, time);

}

BasicFileAttributeView.setTimes(FileTime, FileTime, FileTime) 方法参数分别设置最后修改时间、最后访问时间和创建时间。

关于java - 在Java中设置文件创建时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9198184/

相关文章:

c# - 计算重叠日期的住宿天数

mysql - 从查询 MySQL 中获取 Concat 函数中的本地化月份名称

java - Maven Netbeans 打开的文件太多

python-3.x - 在python内存错误中读取大量文件(20k+)

R 创建函数添加水年列

python - 为什么我在输出文件中看不到实时输出?

swift - 安装时的 Xcode/Swift 默认文件 - iOS

java - 在 Java 中读取 C++ 二进制文件

java - 即使在调用关闭后,进度对话框也会出现泄漏窗口错误

java - 不向 Android 中的 AsyncTask 传递任何内容