문제

이진 파일의 수정 타임 스탬프를 변경하고 싶습니다. 이 작업을 수행하는 가장 좋은 방법은 무엇입니까?

파일을 열고 닫는 것이 좋은 선택일까요? (모든 플랫폼 및 JVM에서 타임 스탬프의 수정이 변경되는 솔루션이 필요합니다).

도움이 되었습니까?

해결책

파일 클래스에는 a가 있습니다 setLastModified 방법. 그것이 개미가하는 일입니다.

다른 팁

내 2 센트 @joe.m 답변

public static void touch(File file) throws IOException{
    long timestamp = System.currentTimeMillis();
    touch(file, timestamp);
}

public static void touch(File file, long timestamp) throws IOException{
    if (!file.exists()) {
       new FileOutputStream(file).close();
    }

    file.setLastModified(timestamp);
}

간단한 스 니펫은 다음과 같습니다.

void touch(File file, long timestamp)
{
    try
    {
        if (!file.exists())
            new FileOutputStream(file).close();
        file.setLastModified(timestamp);
    }
    catch (IOException e)
    {
    }
}

알아요 아파치 개미 a 그것은 바로 그 일을합니다.
참조 소스 터치 코드 (그들이 어떻게하는지 보여줄 수 있습니다)

그들은 사용합니다 FILE_UTILS.setFileLastModified(file, modTime);, 사용하는 ResourceUtils.setLastModified(new FileResource(file), time);, a org.apache.tools.ant.types.resources.Touchable, 구현 org.apache.tools.ant.types.resources.FileResource...

기본적으로, 그것은 전화입니다 File.setLastModified(modTime).

이 질문은 타임 스탬프를 업데이트하는 것을 언급하지만 어쨌든 여기에 넣을 것이라고 생각했습니다. 유니 닉스와 같은 터치를 찾고 있었는데,이 파일이 존재하지 않으면 파일도 생성 할 것입니다.

Apache Commons를 사용하는 사람이라면 누구나 있습니다 FileUtils.touch(File file) 그것은 바로 그렇게합니다.

여기에 있습니다 원천 (인화 openInputStream(File f)):

public static void touch(final File file) throws IOException {
    if (file.exists()) {
        if (file.isDirectory()) {
            throw new IOException("File '" + file + "' exists but is a directory");
        }
        if (file.canWrite() == false) {
            throw new IOException("File '" + file + "' cannot be written to");
        }
    } else {
        final File parent = file.getParentFile();
        if (parent != null) {
            if (!parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("Directory '" + parent + "' could not be created");
            }
        }
        final OutputStream out = new FileOutputStream(file);
        IOUtils.closeQuietly(out);
    }
    final boolean success = file.setLastModified(System.currentTimeMillis());
    if (!success) {
        throw new IOException("Unable to set the last modification time for " + file);
    }
}

이미 사용중인 경우 구아바:

com.google.common.io.Files.touch(file)

부터 File ~이다 나쁜 추상화, 사용하는 것이 좋습니다 Files 그리고 Path:

public static void touch(final Path path) throws IOException {
    Objects.requireNotNull(path, "path is null");
    if (Files.exists(path)) {
        Files.setLastModifiedTime(path, FileTime.from(Instant.now()));
    } else {
        Files.createFile(path);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top