File input/output operations in Java involve reading from and writing to files on the system. The java.io
package provides classes and methods to perform file operations. Here’s an overview of the basic file input/output operations in Java:
File
object, specifying the path to the file.FileReader
or BufferedReader
object, passing the File
object as a parameter.read()
or readLine()
method to read data from the file.close()
method when finished.Example:
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileReadExample { public static void main(String[] args) { try { File file = new File("path/to/file.txt"); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } }
File
object, specifying the path to the file.FileWriter
or BufferedWriter
object, passing the File
object as a parameter.write()
method to write data to the file.close()
method when finished.Example:
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileWriteExample { public static void main(String[] args) { try { File file = new File("path/to/file.txt"); FileWriter fileWriter = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write("Hello, World!"); bufferedWriter.newLine(); // Write a new line bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
Remember to handle exceptions appropriately when working with file input/output operations in Java, as they can occur if the file is not found, permissions are insufficient, or other issues arise.
Copyright ©TechOceanhub All Rights Reserved.