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:
- Reading from a File:
- Create a
File
object, specifying the path to the file. - Create a
FileReader
orBufferedReader
object, passing theFile
object as a parameter. - Use the
read()
orreadLine()
method to read data from the file. - Close the file using the
close()
method when finished.
- Create a
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(); } } }
- Writing to a File:
- Create a
File
object, specifying the path to the file. - Create a
FileWriter
orBufferedWriter
object, passing theFile
object as a parameter. - Use the
write()
method to write data to the file. - Close the file using the
close()
method when finished.
- Create a
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.