Java에서 파일 생성 날짜 결정
StackOverflow ( Java에서 파일 생성 날짜를 얻는 방법) 에 대한 또 다른 유사한 질문이 있지만 OP에는 다른 메커니즘을 통해 해결할 수있는 다른 요구가 있었기 때문에 대답은 실제로 없습니다. 연령별로 정렬 할 수있는 디렉터리에 파일 목록을 만들려고하므로 파일 생성 날짜가 필요합니다.
나는 웹을 많이 트롤링 한 후에 이것을 할 좋은 방법을 찾지 못했습니다. 파일 생성 날짜를 가져 오는 메커니즘이 있습니까?
현재 Windows 시스템에있는 BTW는 Linux 시스템에서도 작동하기 위해이 기능이 필요할 수 있습니다. 또한 생성 날짜 / 시간이 이름에 포함 된 위치에서 파일 명명 규칙을 따를 것이라고 보장 할 수 없습니다.
Java nio 에는 파일 시스템이 제공하는 한 creationTime 및 기타 메타 데이터에 액세스하는 옵션이 있습니다. 확인 이 링크를 밖으로
예를 들어 (@ydaetskcoR의 의견에 따라 제공됨) :
Path file = ...;
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
이 코드로 JDK 7을 사용하여이 문제를 해결했습니다.
package FileCreationDate;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Main
{
public static void main(String[] args) {
File file = new File("c:\\1.txt");
Path filePath = file.toPath();
BasicFileAttributes attributes = null;
try
{
attributes =
Files.readAttributes(filePath, BasicFileAttributes.class);
}
catch (IOException exception)
{
System.out.println("Exception handled when trying to get file " +
"attributes: " + exception.getMessage());
}
long milliseconds = attributes.creationTime().to(TimeUnit.MILLISECONDS);
if((milliseconds > Long.MIN_VALUE) && (milliseconds < Long.MAX_VALUE))
{
Date creationDate =
new Date(attributes.creationTime().to(TimeUnit.MILLISECONDS));
System.out.println("File " + filePath.toString() + " created " +
creationDate.getDate() + "/" +
(creationDate.getMonth() + 1) + "/" +
(creationDate.getYear() + 1900));
}
}
}
이 질문에 대한 후속 조치로-특히 생성 시간과 관련이 있고 새로운 nio 클래스를 통해 얻는 것에 대해 논의하기 때문에 지금 JDK7 구현에서 운이 좋지 않은 것 같습니다. 부록 : OpenJDK7에서도 동일한 동작이 있습니다.
Unix 파일 시스템에서는 생성 타임 스탬프를 검색 할 수 없으며 단순히 마지막 수정 시간의 복사본 만 가져옵니다. 너무 슬프지만 불행히도 사실입니다. 그 이유는 잘 모르겠지만 코드는 다음과 같이 구체적으로 수행합니다.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
public class TestFA {
static void getAttributes(String pathStr) throws IOException {
Path p = Paths.get(pathStr);
BasicFileAttributes view
= Files.getFileAttributeView(p, BasicFileAttributeView.class)
.readAttributes();
System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
}
public static void main(String[] args) throws IOException {
for (String s : args) {
getAttributes(s);
}
}
}
This is a basic example of how to get the creation date of a file in Java
, using BasicFileAttributes
class:
Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt");
BasicFileAttributes attr;
try {
attr = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("Creation date: " + attr.creationTime());
//System.out.println("Last access date: " + attr.lastAccessTime());
//System.out.println("Last modified date: " + attr.lastModifiedTime());
} catch (IOException e) {
System.out.println("oops error! " + e.getMessage());
}
The API of java.io.File
only supports getting the last modified time. And the Internet is very quiet on this topic as well.
Unless I missed something significant, the Java library as is (up to but not yet including Java 7) does not include this capability. So if you were desperate for this, one solution would be to write some C(++) code to call system routines and call it using JNI. Most of this work seems to be already done for you in a library called JNA, though.
You may still need to do a little OS specific coding in Java for this, though, as you'll probably not find the same system calls available in Windows and Unix/Linux/BSD/OS X.
On a Windows system, you can use free FileTimes library.
This will be easier in the future with Java NIO.2 (JDK 7) and the java.nio.file.attribute package.
But remember that most Linux filesystems don't support file creation timestamps.
in java1.7+ You can use this code to get file`s create time !
private static LocalDateTime getCreateTime(File file) throws IOException {
Path path = Paths.get(file.getPath());
BasicFileAttributeView basicfile = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
BasicFileAttributes attr = basicfile.readAttributes();
long date = attr.creationTime().toMillis();
Instant instant = Instant.ofEpochMilli(date);
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
참고URL : https://stackoverflow.com/questions/2723838/determine-file-creation-date-in-java
'IT박스' 카테고리의 다른 글
dapper.net에서 트랜잭션을 사용하는 방법은 무엇입니까? (0) | 2020.08.25 |
---|---|
Swift readonly 외부, readwrite 내부 속성 (0) | 2020.08.25 |
jQuery .data ()는 작동하지 않지만 .attr ()은 작동합니다. (0) | 2020.08.25 |
IntelliJIdea 14 : 트리에서 제외 된 폴더 숨기기 (0) | 2020.08.25 |
단일 테스트 파일 실행 (0) | 2020.08.25 |