Java File Handling

Java File Handling:

Java File Handling refers to the process of creating, reading, updating, and deleting files on a computer’s file system using Java programming language. Java provides built-in classes and methods to perform file handling operations, making it easy for developers to manipulate files.

To create a new file in Java, you can use the File class and its createNewFile() method. Here is an example:

				
					File file = new File("myfile.txt");
try {
boolean created = file.createNewFile();
    if (created) {
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();
}

				
			

To read data from a file, you can use FileReader or BufferedReader class. Here is an example:

				
					try (BufferedReaderbr = new BufferedReader(new FileReader("myfile.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
System.out.println(line);
    }
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}

				
			

To write data to a file, you can use FileWriter or BufferedWriter class. Here is an example:

				
					try (BufferedWriterbw = new BufferedWriter(new FileWriter("myfile.txt"))) {
bw.write("Hello, world!");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}

				
			

To delete a file, you can use the delete() method of the File class. Here is an example:

				
					File file = new File("myfile.txt");
if (file.delete()) {
System.out.println("File deleted successfully!");
} else {
System.out.println("Failed to delete the file.");
}

				
			

These are just a few examples of file handling operations in Java. Java provides many other classes and methods for advanced file handling operations, such as moving files, copying files, etc.

Join To Get Our Newsletter
Spread the love