Validating file path in Java

Import File class

import java.io.File;

Create a new File Instance by giving full pathname String of file/folder

File file = new File("Full-path-to-file-or-folder");

 

  • Checking if File/Folder exists
		if (file.exists()) {
			// File Exists
		} else {
			// File does not exist
		}
  • Check if path specified is a Directory
		if (file.isDirectory()) {
			// Directory
		}
  • Check if application can read/write to file/folder at specified path
		if (file.canRead()) {
			// Application can read File/Folder
		}
		if (file.canWrite()) {
			// Application can write File /Folder
		}
		if (file.canExecute()) {
			// Application can execute file
		}

There may be problems in using canWrite() method in Windows and may not give correct results. Here is a workaround-

Define a method which takes file as input.

Use file.createNewFile() and file.delete() in try block and return true.

If these methods fail then return false in catch block

 

public boolean checkWritable(File file) {
		try {
			file.createNewFile();
			file.delete();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

You can also try opening the file with FileOutputStream and then catch the exceptions.

Leave a Reply

Your email address will not be published. Required fields are marked *