String filePath = args[0];
File file = new File(filePath);
// Check if the file exists and is readable
if (!file.exists() || !file.canRead()) {
System.out.println("Error: The file does not exist or cannot be read.");
System.exit(1);
}
// Check the file extension
String extension = getFileExtension(file);
if (extension.equals("")) {
System.out.println("Error: The file has no extension.");
System.exit(1);
} else if (!extension.equals("txt")) {
System.out.println("Error: Only .txt files are supported. The file has a ." + extension + " extension.");
System.exit(1);
}
// Read and display the first line of the .txt file
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String firstLine = br.readLine();
if (firstLine != null) {
System.out.println(firstLine);
} else {
System.out.println("The file is empty.");
}
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
System.exit(1);
}
// Method to get the file extension
private static String getFileExtension(File file) {
String fileName = file.getName();
int dotIndex = fileName.lastIndexOf(".");
// Check if the dot is not at the beginning of the file name
if (dotIndex > 0) {
return fileName.substring(dotIndex + 1);
} else {
return "";
}
}