Write a java program to Check whether a file can be read or not


This Java code defines a class File_ReadNot with a main method that checks whether a file named "file.txt" in the current working directory can be read.

The try block creates a new File object using the filePath string, and then checks if the file can be read using the canRead method of the File class. If the file can be read, the program prints out a message indicating that the file can be read along with the path of the file. If the file cannot be read, the program prints out a message indicating that the file cannot be read along with the path of the file.

Note that this code assumes that the file "file.txt" exists in the current working directory, and will throw a FileNotFoundException if the file cannot be found.

Source Code

import java.io.*;
public class File_ReadNot
{
	public static void main(String[] args)
	{
		String filePath = "file.txt";
		File f = new File(filePath);
		if (f.canRead())
		{
			System.out.println("File " + f.getPath() + " can be Read");
		}
		else
		{
			System.out.println("File " + f.getPath() + " can Not be Read");
		}
	}
}

Output

File file.txt can be Read