Lab Assignment – 11
1. Write a program in java to read and write into a file using byte stream.
import [Link].*;
class ByteStreamExample {
public static void main(String[] args) {
try {
// Writing into file
FileOutputStream fos = new FileOutputStream("[Link]");
String data = "Hello, this is byte stream example!";
[Link]([Link]());
[Link]();
// Reading from file
FileInputStream fis = new FileInputStream("[Link]");
int i;
while ((i = [Link]()) != -1) {
[Link]((char) i);
}
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
2. Write a program in java to copy the content of file into another file using character stream
import [Link].*;
class CharacterStreamCopy {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");
int i;
while ((i = [Link]()) != -1) {
[Link](i);
}
[Link]();
[Link]();
[Link]("File copied successfully!");
} catch (Exception e) {
[Link](e);
}
}
}
3. Write a program in java to write the object state of a class Student into a file and read the
object and print the details of object on console.
import [Link].*;
// Student class
class Student implements Serializable {
int id;
String name;
Student(int id, String name) {
[Link] = id;
[Link] = name;
}
}
class SerializationExample {
public static void main(String[] args) {
try {
// Writing object
Student s1 = new Student(101, "Prachi");
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](s1);
[Link]();
[Link]();
[Link]("Object written to file");
// Reading object
FileInputStream fis = new FileInputStream("[Link]");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s2 = (Student) [Link]();
[Link]();
[Link]();
[Link]("ID: " + [Link]);
[Link]("Name: " + [Link]);
} catch (Exception e) {
[Link](e);
}
}
}