Created
September 25, 2017 13:38
-
-
Save javamultiplex/5dc2bd894a6169b82c112915bcc49423 to your computer and use it in GitHub Desktop.
How to find last modified date of given file in Java?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex.filehandling; | |
import java.io.File; | |
import java.io.IOException; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
import java.util.Scanner; | |
/** | |
* | |
* @author Rohit Agarwal | |
* @category File Handling | |
* @problem How to get last modified date of given file? | |
* | |
*/ | |
public class FileLastModifiedDate { | |
public static void main(String[] args) throws IOException { | |
Scanner input = null; | |
try { | |
input = new Scanner(System.in); | |
System.out.println("Enter file name with extension : "); | |
String fileName = input.nextLine(); | |
if (isValidFileName(fileName)) { | |
// file is present in current working directory. | |
File file = new File(fileName); | |
if (file.exists()) { | |
long time = file.lastModified(); | |
String dateTime = getStringFromFileTime(time); | |
System.out.println("Last modified date and time is : " + dateTime); | |
} else { | |
System.out.println("File doesn't exist in current directory."); | |
} | |
} else { | |
System.out.println("File name is not valid."); | |
} | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
} | |
} | |
private static String getStringFromFileTime(long time) { | |
Date date = new Date(); | |
// setting milliseconds. | |
date.setTime(time); | |
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a"); | |
// Convert Date to String. | |
String dateTime = dateFormat.format(date); | |
return dateTime; | |
} | |
private static boolean isValidFileName(String fileName) { | |
// Regular expression for validating file name. | |
String pattern = "^.+\\..+$"; | |
boolean result = false; | |
if (fileName.matches(pattern)) { | |
result = true; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment