Displaying file properties can be easily done in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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()); } } } |
- It imports the necessary classes, including
File
andIOException
. - It creates two
File
objects,f
andf1
, representing two different files. - 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. - It attempts to create the second file (
f1
) usingcreateNewFile()
. If the file already exists, it deletes it first and then recreates it. - It sets the second file’s readable status to
true
and writable status tofalse
usingsetReadable()
andsetWritable()
, 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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()); } } } |
- 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. - 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. - It creates a
BufferedReader
object to efficiently read the file line by line. - Inside the
while
loop, it reads each line from the file usingbr.readLine()
and prints it to the console. - 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 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()); } } } |
- 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. - The program uses a
try-with-resources
block to open and manage the file input stream. It also opens the Excel workbook. - It assumes that the Excel file has only one sheet and accesses it using
workbook.getSheetAt(0)
. - It iterates through the rows and columns of the sheet, checking the cell type and printing the cell contents accordingly.
- 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