Created
September 25, 2017 13:17
-
-
Save javamultiplex/262e890c1d1797ddeab9ec340a9bb29e to your computer and use it in GitHub Desktop.
How to delete 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.util.Scanner; | |
/** | |
* @author Rohit Agarwal | |
* @category File Handling | |
* @problem How to delete given file in Java? | |
* | |
*/ | |
public class DeleteFile { | |
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()) { | |
boolean deleted = file.delete(); | |
if (deleted) { | |
System.out.println("File is deleted successfully."); | |
} else { | |
System.out.println("Some error occured. Try again!!"); | |
} | |
} else { | |
System.out.println("File is not present in current directory."); | |
} | |
} else { | |
System.out.println("File name is not valid."); | |
} | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
} | |
} | |
private static boolean isValidFileName(String fileName) { | |
// Regular expression that checks whether given file name is valid or | |
// not. | |
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