Java I/O (Input/Output) operations refer to the process of reading data from input sources and writing data to output destinations. Java provides a comprehensive set of classes and methods in the java.io
package to perform I/O operations.
Here’s an example of how Java I/O operations can be used to read and write information about cars:
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 55 56 57 58 59 60 |
import java.io.*; class Car implements Serializable { private String make; private String model; private int year; private int speed; public Car(String make, String model, int year, int speed) { this.make = make; this.model = model; this.year = year; this.speed = speed; } public String getMake() { return make; } public String getModel() { return model; } public int getYear() { return year; } public int getSpeed() { return speed; } @Override public String toString() { return make + " " + model + " " + year + " " + speed; } } public class CarIOExample { public static void main(String[] args) { Car car = new Car("Toyota", "Camry", 2019, 120); // Write car information to a file try (FileOutputStream fos = new FileOutputStream("car.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(car); } catch (IOException e) { e.printStackTrace(); } // Read car information from a file try (FileInputStream fis = new FileInputStream("car.ser"); ObjectInputStream ois = new ObjectInputStream(fis)) { Car readCar = (Car) ois.readObject(); System.out.println("Read car: " + readCar); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } |
In this example, a Car
class is defined, which implements the Serializable
interface. This allows objects of the Car
class to be written to and read from a file. The main
method creates a Car
object, writes it to a file using an ObjectOutputStream
, and then reads it back using an ObjectInputStream
. The read Car
object is then printed to the console to demonstrate that the information was correctly written to and read from the file.Regenerate response