If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To demonstrate file handling in Java and how to create a new file and get information about it, we'll create a program that creates a new text file, writes some data to it, and then retrieves information about the file.
Here's the code to achieve this:
javaCopy codeimport java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileHandlingExample {
public static void main(String[] args) {
// Step 1: Create a new file
File file = new File("sample.txt");
try {
if (file.createNewFile()) {
System.out.println("File created successfully.");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
e.printStackTrace();
}
// Step 2: Write data to the file
try (FileWriter writer = new FileWriter(file)) {
writer.write("Hello, this is a sample text.\n");
writer.write("Writing data to a file in Java.");
System.out.println("Data written to the file successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
// Step 3: Get information about the file
if (file.exists()) {
System.out.println("File name: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("File size: " + file.length() + " bytes");
System.out.println("Is file readable: " + file.canRead());
System.out.println("Is file writable: " + file.canWrite());
System.out.println("Is file executable: " + file.canExecute());
System.out.println("Is file a directory: " + file.isDirectory());
System.out.println("Is file a regular file: " + file.isFile());
} else {
System.out.println("File does not exist.");
}
}
}
Explanation:
We create a File
object called file
representing the file "sample.txt" in the current working directory.
We use the createNewFile()
method to create the new file. If the file already exists, it won't be created again.
We use a FileWriter
to write data to the file.
To get information about the file, we check its existence using exists()
and then use various methods from the File
class to get information like the file name, absolute path, size, and whether it's a directory or a regular file.
Make sure to handle exceptions properly and close the resources using try-with-resources for efficient and robust file handling.
Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.
Comments: 0