From 17981c9036fcb285ecb791b61be7d01eef124c55 Mon Sep 17 00:00:00 2001 From: vunamtien Date: Sat, 11 Dec 2021 13:35:40 +0700 Subject: [PATCH] BAEL-5052-simulate-touch-command-in-java (#11560) * BAEL-5052-simulate-touch-command-in-java * refactor Co-authored-by: tienvn4 --- .../simulation/touch/command/Simulator.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 core-java-modules/core-java-io-4/src/main/java/com/baeldung/simulation/touch/command/Simulator.java diff --git a/core-java-modules/core-java-io-4/src/main/java/com/baeldung/simulation/touch/command/Simulator.java b/core-java-modules/core-java-io-4/src/main/java/com/baeldung/simulation/touch/command/Simulator.java new file mode 100644 index 0000000000..403981e078 --- /dev/null +++ b/core-java-modules/core-java-io-4/src/main/java/com/baeldung/simulation/touch/command/Simulator.java @@ -0,0 +1,49 @@ +package com.baeldung.simulation.touch.command; + +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.attribute.FileTime; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class Simulator { + + public static void touch(String path, String... args) throws IOException, ParseException { + File file = new File(path); + if (!file.exists()) { + file.createNewFile(); + if (args.length == 0) { + return; + } + } + long timeMillis = args.length < 2 ? System.currentTimeMillis() : new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").parse(args[1]).getTime(); + if (args.length > 0) { + // change access time only + if ("a".equals(args[0])) { + FileTime accessFileTime = FileTime.fromMillis(timeMillis); + Files.setAttribute(file.toPath(), "lastAccessTime", accessFileTime); + return; + } + // change modification time only + if ("m".equals(args[0])) { + file.setLastModified(timeMillis); + return; + } + } + // other cases will change both + FileTime accessFileTime = FileTime.fromMillis(timeMillis); + Files.setAttribute(file.toPath(), "lastAccessTime", accessFileTime); + file.setLastModified(timeMillis); + } + + public static void touchWithApacheCommons(String path) throws IOException { + FileUtils.touch(new File(path)); + } + + public static void main(String[] args) throws IOException, ParseException { + touch("test.txt"); + } +}