|
| 1 | +package com.baeldung.simulation.touch.command; |
| 2 | + |
| 3 | +import org.apache.commons.io.FileUtils; |
| 4 | + |
| 5 | +import java.io.File; |
| 6 | +import java.io.IOException; |
| 7 | +import java.nio.file.Files; |
| 8 | +import java.nio.file.attribute.FileTime; |
| 9 | +import java.text.ParseException; |
| 10 | +import java.text.SimpleDateFormat; |
| 11 | + |
| 12 | +public class Simulator { |
| 13 | + |
| 14 | + public static void touch(String path, String... args) throws IOException, ParseException { |
| 15 | + File file = new File(path); |
| 16 | + if (!file.exists()) { |
| 17 | + file.createNewFile(); |
| 18 | + if (args.length == 0) { |
| 19 | + return; |
| 20 | + } |
| 21 | + } |
| 22 | + long timeMillis = args.length < 2 ? System.currentTimeMillis() : new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").parse(args[1]).getTime(); |
| 23 | + if (args.length > 0) { |
| 24 | + // change access time only |
| 25 | + if ("a".equals(args[0])) { |
| 26 | + FileTime accessFileTime = FileTime.fromMillis(timeMillis); |
| 27 | + Files.setAttribute(file.toPath(), "lastAccessTime", accessFileTime); |
| 28 | + return; |
| 29 | + } |
| 30 | + // change modification time only |
| 31 | + if ("m".equals(args[0])) { |
| 32 | + file.setLastModified(timeMillis); |
| 33 | + return; |
| 34 | + } |
| 35 | + } |
| 36 | + // other cases will change both |
| 37 | + FileTime accessFileTime = FileTime.fromMillis(timeMillis); |
| 38 | + Files.setAttribute(file.toPath(), "lastAccessTime", accessFileTime); |
| 39 | + file.setLastModified(timeMillis); |
| 40 | + } |
| 41 | + |
| 42 | + public static void touchWithApacheCommons(String path) throws IOException { |
| 43 | + FileUtils.touch(new File(path)); |
| 44 | + } |
| 45 | + |
| 46 | + public static void main(String[] args) throws IOException, ParseException { |
| 47 | + touch("test.txt"); |
| 48 | + } |
| 49 | +} |
0 commit comments