Displaying file properties

Displaying file properties can be easily done in java

  1. It imports the necessary classes, including File and IOException.
  2. It creates two File objects, f and f1, representing two different files.
  3. It checks if the first file (f) exists and whether it’s a directory or a regular file. If it’s a regular file, it prints various properties like name, path, absolute path, and more.
  4. It attempts to create the second file (f1) using createNewFile(). If the file already exists, it deletes it first and then recreates it.
  5. It sets the second file’s readable status to true and writable status to false using setReadable() and setWritable(), respectively. It then checks if the file can be written to.

Overall, this program demonstrates how to work with files and directories in Java, including checking file properties, creating and deleting files, and setting file permissions.

Q: Write a Java Program to read text file

  1. You specify the path to the text file you want to read by setting the filePath variable. Replace "C:\\example\\file.txt" with the actual path to your text file.
  2. The program uses a try-with-resources block to open and manage the file input stream. This ensures that the file stream is automatically closed when it’s no longer needed.
  3. It creates a BufferedReader object to efficiently read the file line by line.
  4. Inside the while loop, it reads each line from the file using br.readLine() and prints it to the console.
  5. If any errors occur while reading the file, such as the file not existing, an IOException is caught and an error message is displayed.

Q: Write a Java Program to Excel file

To read an Excel file in Java, you can use the Apache POI library, which provides classes for working with Excel files.

  1. ou specify the path to the Excel file you want to read by setting the filePath variable. Replace "C:\\example\\sample.xlsx" with the actual path to your Excel file.
  2. The program uses a try-with-resources block to open and manage the file input stream. It also opens the Excel workbook.
  3. It assumes that the Excel file has only one sheet and accesses it using workbook.getSheetAt(0).
  4. It iterates through the rows and columns of the sheet, checking the cell type and printing the cell contents accordingly.
  5. If any errors occur while reading the Excel file, such as the file not existing or being in an unsupported format, an IOException is caught, and an error message is displayed.

Read More

Reading a file using FileInputStream

User Defined exception in Java | Java custom exception examples