Displaying file properties

Displaying file properties can be easily done in java

package io;

import java.io.File;
import java.io.IOException;

public class FileOrDir {

    public static void main(String[] args) {
        File f = new File("D:\\first.txt");
        File f1 = new File("D:\\second.txt");
        if (f.exists() == false) {
            System.out.println("File  or Directory does not exists");
        }
        if (f.isDirectory()) {
            System.out.println("This is a directory");
        }
        if (f.isFile()) {
            System.out.println("This is a file");
            System.out.println("File name :" + f.getName());
            System.out.println("File path :" + f.getPath());
            System.out.println("File Absolute path :" + f.getAbsolutePath());
            try {
                System.out.println("File Canonical path :" + f.getCanonicalPath());
            } catch (IOException ex) {
                System.out.println("IOException " + ex);
            }
            System.out.println("File Parent :" + f.getParent());
            System.out.println("File can execute :" + f.canExecute());
            System.out.println("File can read :" + f.canRead());
            System.out.println("File can write :" + f.canWrite());
            System.out.println("File last Modified :" + f.lastModified());
            try {

                if (f1.createNewFile()) {
                    System.out.println("File created ");
                } else {
                    if (f1.exists()) {
                        System.out.println("File already exists ");
                        f1.delete();
                        System.out.println("File is get deleted ");
                        if (f1.createNewFile()) {
                            System.out.println("now File created ");
                        }
                    }
                }
            } catch (IOException ex) {
                System.out.println("IOException " + ex);
            }
            System.out.println("Setting the file readable status :" + f1.setReadable(true));
            System.out.println("Setting the file writable status :" + f1.setWritable(false));
            System.out.println("Can we write on file :" + f1.canWrite());
        }
    }
}

  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

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadTextFile {
    public static void main(String[] args) {
        // Specify the path to the text file you want to read
        String filePath = "C:\\example\\file.txt"; // Replace with the actual file path

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;

            System.out.println("Contents of the text file:");

            // Read and print each line from the file
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("Error reading the file: " + e.getMessage());
        }
    }
}



  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.

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadExcelFile {
    public static void main(String[] args) {
        // Specify the path to the Excel file you want to read
        String filePath = "C:\\example\\sample.xlsx"; // Replace with the actual file path

        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis)) {
            // Assuming the Excel file has only one sheet, you can access it like this:
            Sheet sheet = workbook.getSheetAt(0);

            // Iterate through rows and columns to read the data
            for (Row row : sheet) {
                for (Cell cell : row) {
                    // Check the cell type and process accordingly
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            if (DateUtil.isCellDateFormatted(cell)) {
                                System.out.print(cell.getDateCellValue() + "\t");
                            } else {
                                System.out.print(cell.getNumericCellValue() + "\t");
                            }
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        case BLANK:
                            System.out.print("\t");
                            break;
                        default:
                            System.out.print("\t");
                            break;
                    }
                }
                System.out.println(); // Move to the next line for the next row
            }
        } catch (IOException e) {
            System.err.println("Error reading the Excel file: " + e.getMessage());
        }
    }
}



  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