gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:49:31 27 4
gpt4 key购买 nike

我知道设置创建时间戳在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com